Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a file in a directory and sub directories using Java 8

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?

like image 770
KayV Avatar asked Dec 08 '16 11:12

KayV


People also ask

How do you find subdirectories in Java?

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.

How do I search for a file in a subfolder?

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.

How can I get a list of all the subfolders and files present in a directory using PHP?

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.


2 Answers

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();
}
like image 189
Anton Balaniuc Avatar answered Oct 18 '22 22:10

Anton Balaniuc


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...

like image 41
KayV Avatar answered Oct 18 '22 23:10

KayV