I need a to find file according to its name in directory tree. And then show a path to this file. I found something like this, but it search according extension. Could anybody help me how can I rework this code to my needs...thanks
public class filesFinder {
public static void main(String[] args) {
File root = new File("c:\\test");
try {
String[] extensions = {"txt"};
boolean recursive = true;
Collection files = FileUtils.listFiles(root, extensions, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
System.out.println(file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Searching files in Java can be performed using the File class and FilenameFilter interface. The FilenameFilter interface is used to filter files from the list of files. This interface has a method boolean accept(File dir, String name) that is implemented to find the desired files from the list returned by the java. io.
The ls command is used to list files or directories in Linux and other Unix-based operating systems. Just like you navigate in your File explorer or Finder with a GUI, the ls command allows you to list all files or directories in the current directory by default, and further interact with them via the command line.
To test to see if a file or directory exists, use the exists method of the Java File class, as shown in this example: File tmpDir = new File("/var/tmp"); boolean exists = tmpDir. exists(); The existing method of the Java File class returns true if the file or directory exists, and false otherwise.
The List() method. This method returns a String array which contains the names of all the files and directories in the path represented by the current (File) object. Using this method, you can just print the names of the files and directories.
public class Test {
public static void main(String[] args) {
File root = new File("c:\\test");
String fileName = "a.txt";
try {
boolean recursive = true;
Collection files = FileUtils.listFiles(root, null, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
if (file.getName().equals(fileName))
System.out.println(file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Recursive directory search in Java is pretty darn easy. The java.io.File
class has a listFiles()
method that gives all the File
children of a directory; there's also an isDirectory()
method you call on a File
to determine whether you should recursively search through a particular child.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With