In Java, you can use the Files.list()
method to list all files in a given directory. Files.list(Path dir)
is a method in the java.nio.file.Files
class.
This method returns a Stream
that is lazily populated with Path
by walking the directory tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path
objects that are obtained as if by resolving the name of the directory entry against dir
.
The stream is “lazy” because not all the Paths
are populated at once. This can be beneficial if you have a large number of files in your directory.
Here’s a code snippet that shows you how to do it:
package org.kodejava.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ListFiles {
public static void main(String[] args) {
// Replace with your directory
Path path = Paths.get("D:/Games");
// Use try-with-resources to get auto-closeable stream
try (Stream<Path> paths = Files.list(path)) {
paths
.filter(Files::isRegularFile) // filter out subdirectories
.forEach(System.out::println); // print file names
} catch (IOException e) {
e.printStackTrace();
}
}
}
This code lists all files in the specified directory ("D:/Games"
in this case). It uses a stream of Path
obtained from Files.list()
, filters out the paths that are not regular files using Files.isRegularFile()
, and finally prints each file name using System.out.println()
.
Remember to replace "D:/Games"
with the actual directory you want to list files from. Also, the Files.list()
method throws an IOException
, so you must handle this exception in a try-catch block or declare it in the method signature.
- How do I create a servlet filter to make secure cookies? - April 18, 2024
- How do I configure secure cookies using web.xml? - April 18, 2024
- How do I create a table with multiple header in iText 8? - March 16, 2024