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!