This example demonstrates how we can use the FileUtils
class listFiles()
method to search for a file specified by their extensions. We can also define to find the file recursively deep down into the subdirectories.
package org.kodejava.commons.io;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.Collection;
public class SearchFileRecursive {
public static void main(String[] args) {
File root = new File("F:/Wayan/Kodejava/kodejava-example");
try {
String[] extensions = {"xml", "java", "dat"};
// Find files within a root directory and optionally its
// subdirectories, which match an array of extensions. When the
// extensions are null, all files will be returned.
//
// This method will return matched file as java.io.File
Collection<File> files = FileUtils.listFiles(root, extensions, true);
for (File file : files) {
System.out.println("File = " + file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.14.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024