Java - Search for files in a directory

前端 未结 9 681
予麋鹿
予麋鹿 2020-11-29 05:12

This is supposed to be simple, but I can\'t get it - \"Write a program that searches for a particular file name in a given directory.\" I\'ve found a few examples of a hardc

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 05:20

    Using Java 8+ features we can write the code in few lines:

    protected static Collection find(String fileName, String searchDirectory) throws IOException {
        try (Stream files = Files.walk(Paths.get(searchDirectory))) {
            return files
                    .filter(f -> f.getFileName().toString().equals(fileName))
                    .collect(Collectors.toList());
    
        }
    }
    

    Files.walk returns a Stream which is "walking the file tree rooted at" the given searchDirectory. To select the desired files only a filter is applied on the Stream files. It compares the file name of a Path with the given fileName.

    Note that the documentation of Files.walk requires

    This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open directories are closed promptly after the stream's operations have completed.

    I'm using the try-resource-statement.


    For advanced searches an alternative is to use a PathMatcher:

    protected static Collection find(String searchDirectory, PathMatcher matcher) throws IOException {
        try (Stream files = Files.walk(Paths.get(searchDirectory))) {
            return files
                    .filter(matcher::matches)
                    .collect(Collectors.toList());
    
        }
    }
    

    An example how to use it to find a certain file:

    public static void main(String[] args) throws IOException {
        String searchDirectory = args[0];
        String fileName = args[1];
        PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:.*" + fileName);
        Collection find = find(searchDirectory, matcher);
        System.out.println(find);
    }
    

    More about it: Oracle Finding Files tutorial

提交回复
热议问题