Nice to meet you, I am a first year web engineer who started working as a new graduate in April this year. This is the first post! We will continue to output the skills and skills that we have learned in the future. I would appreciate it if you could comment if you made a mistake in the code or if this is better. Thank you!
Create a method (searchFile method) that acquires the path containing a specific file from a directory whose number of layers is unknown and outputs it. Here, search under "C: \ tmp" and return the file path including "hoge" in the file name.
Eclipse Oxygen Java8
Store the directory / file list of the path specified by the listFile method in an array
Take out the acquired contents in a loop, evaluate whether it is a file, and conditional branch a. File → Evaluate whether the file you want b. Others → Recursive call to searchFile method
main.java
import java.io.File;
public class Main {
public static void main(String[] args) {
//Specify the path you want to search
searchFile("/tmp/");
}
public static void searchFile(String targetPath) {
File dir = new File(targetPath);
//Directory under the path/Put the files in an array
File[] list = dir.listFiles();
for(File path : list) {
if(path.isFile()) {
//Divide the obtained path with a backslash"\\"not"\\\\"give
String[] splitedPath = path.toString().split("\\\\");
String file = splitedPath[splitedPath.length-1];
if(file.toString().contains("hoge")) {
System.out.println(path);
}
//Recursive method call if file is not a file
}else {
searchFile(path.toString());
}
}
}
}
result
\tmp\hogehoge\hoge.txt
In order to search all directories for which the number of layers is unknown, I think the point is to make a recursive call that calls itself in a conditional branch.
Recommended Posts