How to implement an algorithm in Java 8, given a start directory and a filename, that searches for the file in the given directory or any sub-directories which are nested not deeper than 5 levels.
For example consider the following directory structure:
Folder 1
Folder 2
Folder 3
Folder 4
Folder 5
Folder 6
nfiles.txt....
MyFile.txt
xfile.txt
filesInFolder4....
filesInFolder3...
.....
The algorithm should search for the file up to files containd in the Folder 5 and report if a file with given filename exists?
How to do that using Java 8?
You can use String[] directories = file. list() to list all file names, then use loop to check each sub-files and use file. isDirectory() function to get subdirectories.
Open Windows Explorer. Select Organize / Folder and Search options. Select the Search Tab. In the How to search section, select the Include subfolders in search results when searching in file folders option.
PHP using scandir() to find folders in a directory The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.
Please have a look at Files.find method.
try (Stream<Path> stream = Files.find(Paths.get("Folder 1"), 5,
(path, attr) -> path.getFileName().toString().equals("Myfile.txt") )) {
System.out.println(stream.findAny().isPresent());
} catch (IOException e) {
e.printStackTrace();
}
I find solution working with Files.find and Files.walk as follows:
// Finding a file upto x level in File Directory using NIO Files.find
Path start = Paths.get("/Users/***/Documents/server_pull");
int maxDepth = 5;
try(Stream<Path> stream = Files.find(start,
maxDepth,
(path, attr) -> String.valueOf(path).endsWith(".json"))){
String fileName = stream
.sorted()
.map(String::valueOf)
.filter((path) -> {
//System.out.println("In Filter : "+path);
return String.valueOf(path).endsWith("system_health_12_55_TestServer.json");
})
.collect(Collectors.joining());
System.out.println("fileName : "+fileName);
}catch(Exception e){
e.printStackTrace();
}
// Finding a file upto x level in File Directory using NIO Files.walk
Path startWalk = Paths.get("/Users/***/Documents/server_pull");
int depth = 5;
try( Stream<Path> stream1 = Files.walk(startWalk,
depth)){
String walkedFile = stream1
.map(String::valueOf)
.filter(path -> {
return String.valueOf(path).endsWith("system_health_12_55_TestServer.json");
})
.sorted()
.collect(Collectors.joining());
System.out.println("walkedFile = "+walkedFile);
}catch(Exception e){
e.printStackTrace();
}
It seems more simpler than walkFileTree...
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