Home  >  Article  >  Java  >  How to List All Files in a Directory Using Java?

How to List All Files in a Directory Using Java?

DDD
DDDOriginal
2024-10-27 06:59:03855browse

How to List All Files in a Directory Using Java?

How to Obtain File Names from a Directory

Question:

Devise a method to retrieve a list containing the file names within a specified directory. The desired output is a list of file names (e.g., ["000", "012", "013"]).

Answer:

To achieve this, utilize the following code snippet in Java:

<code class="java">import java.io.File;

public class FileLister {

    public static void main(String[] args) {
        File folder = new File("your/path");
        File[] listOfFiles = folder.listFiles();
        if (listOfFiles != null) {
            for (File file : listOfFiles) {
                if (file.isFile()) {
                    System.out.println("File " + file.getName());
                } else if (file.isDirectory()) {
                    System.out.println("Directory " + file.getName());
                }
            }
        }
    }
}</code>

Additional Note:

The provided code retrieves all file types within the directory. To specify a desired file type (e.g., JPEG), add the following filter to the listFiles() method:

<code class="java">File[] listOfFiles = folder.listFiles(new FileFilter() {
    @Override
    public boolean accept(File file) {
        return file.getName().endsWith(".jpg");
    }
});</code>

The above is the detailed content of How to List All Files in a Directory Using 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