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!