Find files in a folder using Java

前端 未结 12 1944
日久生厌
日久生厌 2020-11-28 08:15

What I need to do if Search a folder say C:\\example

I then need to go through each file and check to see if it matches a few start characters so if fil

12条回答
  •  我在风中等你
    2020-11-28 08:29

    • Matcher.find and Files.walk methods could be an option to search files in more flexible way
    • String.format combines regular expressions to create search restrictions
    • Files.isRegularFile checks if a path is't directory, symbolic link, etc.

    Usage:

    //Searches file names (start with "temp" and extension ".txt")
    //in the current directory and subdirectories recursively
    Path initialPath = Paths.get(".");
    PathUtils.searchRegularFilesStartsWith(initialPath, "temp", ".txt").
                                           stream().forEach(System.out::println);
    

    Source:

    public final class PathUtils {
    
        private static final String startsWithRegex = "(? searchRegularFilesStartsWith(final Path initialPath, 
                                 final String fileName, final String fileExt) throws IOException {
            return searchRegularFiles(initialPath, startsWithRegex + fileName, fileExt);
        }
    
        public static List searchRegularFilesEndsWith(final Path initialPath, 
                                 final String fileName, final String fileExt) throws IOException {
            return searchRegularFiles(initialPath, fileName + endsWithRegex, fileExt);
        }
    
        public static List searchRegularFilesAll(final Path initialPath) throws IOException {
            return searchRegularFiles(initialPath, "", "");
        }
    
        public static List searchRegularFiles(final Path initialPath,
                                 final String fileName, final String fileExt)
                throws IOException {
            final String regex = String.format(containsRegex, fileName, fileExt);
            final Pattern pattern = Pattern.compile(regex);
            try (Stream walk = Files.walk(initialPath.toRealPath())) {
                return walk.filter(path -> Files.isRegularFile(path) &&
                                           pattern.matcher(path.toString()).find())
                        .collect(Collectors.toList());
            }
        }
    
        private PathUtils() {
        }
    }
    

    Try startsWith regex for \txt\temp\tempZERO0.txt:

    (?

    Try endsWith regex for \txt\temp\ZERO0temp.txt:

    temp(?=[\\.\\n])(?:[^\/\\]*(?=((?i)\.txt(?!.))))
    

    Try contains regex for \txt\temp\tempZERO0tempZERO0temp.txt:

    temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))
    

提交回复
热议问题