Home > Java > javaTutorial > 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
Release: 2024-10-26 13:50:30
Original
933 people have browsed it

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>
Copy after login

2. Retrieve File List:

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

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template