Home  >  Article  >  Java  >  How to Get a List of Filenames from a Directory in Java?

How to Get a List of Filenames from a Directory in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 13:50:30836browse

How to Get a List of Filenames from a Directory in Java?

Obtaining Filenames from a Directory

To create a list of filenames within a folder, follow these steps:

1. Initialize the File Object:

<code class="java">File folder = new File("path/to/directory");</code>

2. Retrieve File List:

<code class="java">File[] listOfFiles = folder.listFiles();</code>

3. Iterate over File List and Check Type:

<code class="java">if (listOfFiles != null) {
 for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
    // Extract and store filename
  } else if (listOfFiles[i].isDirectory()) {
    // Process directory if necessary
  }
 }
}</code>

4. Filter Based on File Type (Optional):

<code class="java">// Filter for JPEG files if needed
if (file.getName().endsWith(".jpg")) {
  // Add filename to list
}</code>

This code snippet demonstrates how to retrieve all filenames from a directory. You can specify further criteria, such as file types, by modifying the if conditions in step 4 as necessary.

The above is the detailed content of How to Get a List of Filenames from a Directory in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn