So you can have more options, try the Java 7 NIO way of doing this
public static void main(String[] args) throws Exception {
try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/"))) {
for (Path path : files) {
System.out.println(path.toString());
}
}
}
You can also provide a filter for the paths in the form of a DirectoryStream.Filter
implementation
public static void main(String[] args) throws Exception {
try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/"),
new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
return true; // or whatever you want
}
})
) {
for (Path path : files) {
System.out.println(path.toString());
}
}
}
Obviously you can extract the anonymous class to an actual class declaration.
Note that this solution cannot return null
like the listFiles()
solution.
For a recursive solution, check out the FileVisitor
interface. For path matching, use the PathMatcher
interface along with FileSystems
and FileSystem
. There are examples floating around Stackoverflow.