How to get a specific number of files from a directory? [duplicate]

99封情书 提交于 2019-12-08 05:13:10

问题


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.


回答1:


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); 



回答2:


// Point to the directory
File directory = new File("C:/StroedFiles");
// Get a listing of all files in the directory
String[] filesInDir = directory.list();
// Grab as many files you want
for ( int i=0; i<50; i++ )
{
  System.out.println( "file: " + filesInDir[i] );
}



回答3:


A suggestion for a suitable FileFilter implementation...

public class LimitedFileFilter implements java.io.FileFilter {
    private int counter;
    private int limit;

    public LimitedFileFilter(int lim) {
        if (lim <= 0) {
            throw new IllegalArgumentException("Non-positive limit.");
        }
        limit = lim;
    }

    @Override
    public boolean accept(File name) {
        if (counter < limit &&
            name.isFile()   &&
            (name.getName().contains("key1")) {
            counter++;
            return true;
        }
        else {
            return false;
        }
    }
}


来源:https://stackoverflow.com/questions/48765712/how-to-get-a-specific-number-of-files-from-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!