I need to get a list of all the files in a directory, including files in all the sub-directories. What is the standard way to accomplish directory iteration with Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Check out the FileUtils class in Apache Commons - specifically iterateFiles:
If you are using Java 1.7, you can use
java.nio.file.Files.walkFileTree(...)
.For example:
If you are using Java 8, you can use the stream interface with
java.nio.file.Files.walk(...)
:You can use
File#isDirectory()
to test if the given file (path) is a directory. If this istrue
, then you just call the same method again with itsFile#listFiles()
outcome. This is called recursion.Here's a basic kickoff example.
Note that this is sensitive to
StackOverflowError
when the tree is deeper than the JVM's stack can hold. You may want to use an iterative approach or tail-recursion instead, but that's another subject ;)It's a tree, so recursion is your friend: start with the parent directory and call the method to get an array of child Files. Iterate through the child array. If the current value is a directory, pass it to a recursive call of your method. If not, process the leaf file appropriately.
To add with @msandiford answer, as most of the times when a file tree is walked u may want to execute a function as a directory or any particular file is visited. If u are reluctant to using streams. The following methods overridden can be implemented
For Java 7+, there is also https://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html
Example taken from the Javadoc: