Whenever possible prefer the new Java 8 API that uses the class 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 method Paths.get()
. Note that this method can receive an arbitrary amount of parameters, so you no longer have to worry about bars, 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
(a) means that I am listing only the current directory. To read all subdirectories, use Integer.MAX_VALUE
.
The third parameter receives FileVisitOption.FOLLOW_LINKS
to indicate to Java that it should consider the shortcuts as used in linux/Unix. I consider it important to always use this parameter.
The method walk
returns a Stream
, which is the functional form of Java 8 to traverse a sequence of elements. The forEach
allows you to execute a command for each element of the Stream
, which in this case prints the absolute path within the expression lambda.
If you want to, for example, filter file types, you can do so:
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 that end 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 filter the files at the time of listing, the method Files.find
. 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 file attributes. In case, I am checking if it is a normal file and not a directory or symbol using attributes.isRegularFile()
.
It would be interesting to remove the swing components as this is irrelevant to the solution of the problem.
– user28595
Yes, of course! I actually posted the code I’m using here. But it was worth the alert!
– Fabio Klevinskas Lopes