Home > Java > javaTutorial > body text

How to List All Files in a Directory Using Java?

DDD
Release: 2024-10-27 06:59:03
Original
854 people have browsed it

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!