Getting the filenames of all files in a folder
To get the filenames of all files in a folder in Java, you can use the File class and its list method.
To get the filenames of all files in a folder in Java, you can use the File class and its listFiles method.
Here's an example:
import java.io.File;
File folder = new File("/path/to/folder");
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null) {
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println(file.getName());
}
}
}This will print the filenames of all files in the specified folder. Note that FileFilter only filters the immediate directory contents and does not recurse. For recursive file listing, the modern java.nio.file.Files API is recommended.
Here's an example:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.stream.Stream;
Path folder = Paths.get("/path/to/folder");
try (Stream<Path> stream = Files.walk(folder)) {
stream.filter(Files::isRegularFile)
.forEach(path -> System.out.println(path.getFileName()));
} catch (IOException e) {
e.printStackTrace();
}This will print the filenames of all files in the specified folder and its subfolders.