Search code examples
javafilejava-7filefilter

How to get a specific number of files from a directory?


I want to retrieve files based on settings i have provided in a properties file. e.g. i just want to get 50 files in first iteration and stop getting all may be there are thousands of files in the folder.

How can i just randomly get 50 files and do not get all list or iterate over files to get 50 ?

filesList = folder.listFiles( new FileFilter() {                
    @Override
    public boolean accept(File name) {                      
        return (name.isFile() && ( name.getName().contains("key1")));
    }
});

EDIT: i have removed the for statement. Even if I have provided just one folder to fetch from it will fetch all files, counter variable still loops over all files in the folder not a good solution.


Solution

  • Use Files and Path from the java.nio API instead of File.

    You can also use them with Stream in Java 8 :

    Path folder = Paths.get("...");
    List<Path> collect = Files.walk(folder)
                              .filter(p -> Files.isRegularFile(p) && p.getFileName().toString().contains("key1"))
                              .limit(50)
                              .collect(Collectors.toList());
    

    In Java 7, you could stop the file walking by using a SimpleFileVisitor implementation that takes care to terminate as 50 files matched the predicate:

    List<Path> filteredFiles = new ArrayList<>();
    
    SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (Files.isRegularFile(file) && file.getFileName()
                                                 .toString()
                                                 .contains("key1")) {
                filteredFiles.add(file);
            }
    
            if (filteredFiles.size() == 50) {
                return FileVisitResult.TERMINATE;
            }
            return super.visitFile(file, attrs);
        }
    };
    

    and how use it :

    final Path folder = Paths.get("...");
    
    // no limitation in the walking depth 
    Files.walkFileTree(folder, visitor);
    
    // limit the walking depth to 1 level
    Files.walkFileTree(folder, new HashSet<>(), 1, visitor);