Whenever possible, prefer the new Java 8 API that uses the Path
.
For example, you can list the files in a directory like this:
Files.walk(Paths.get("/tmp"), 1, FileVisitOption.FOLLOW_LINKS)
.forEach(path -> System.out.printf("%s%n", path.toAbsolutePath().toString()));
The first parameter is the directory itself, which is a Path
built using the Paths.get()
method. Note that this method can receive an arbitrary amount of parameters, so you no longer have to worry about slashes, because you can always specify each component of the path in a separate parameter.
The second argument defines whether the routine will read subdirectories. In this case, 1
(one) means that I'm only listing the current directory. To read all subdirectories, use Integer.MAX_VALUE
.
The third parameter receives FileVisitOption.FOLLOW_LINKS
to tell Java that it should consider the shortcuts as used in linux / unix. I consider it important to always use this parameter.
The walk
method returns a Stream
, which is the Java 8 functional way of traversing a sequence of elements. The forEach
allows executing a command for each element of Stream
, which in this case prints the absolute path inside the lambda expression.
If you want to, for example, filter the file types, you can do this:
Files.walk(Paths.get("/tmp"), 1, FileVisitOption.FOLLOW_LINKS)
.filter(path -> path.toString().endsWith(".log"))
.forEach(path -> System.out.printf("%s%n", path.toAbsolutePath().toString()));
The difference here is the filter
that leaves in the Stream
all paths ending with .log
. The syntax may not be easy at first, but what the code does is pretty obvious.
Finally, there is a shortcut to already filtering the files at the time of listing, the Files.find
method. Example:
Files.find(Paths.get("/tmp"), 1,
(path, attributes) -> attributes.isRegularFile() && path.toString().endsWith(".log"),
FileVisitOption.FOLLOW_LINKS
).forEach(path -> System.out.println(path.toAbsolutePath()));
This method is more efficient and allows you to easily access the attributes of the file. In case, I'm checking if it's a normal file and not a directory or symbol using attributes.isRegularFile()
.