如何从目录中获取特定数量的文件? [英] How to get a specific number of files from a directory?

查看:138
本文介绍了如何从目录中获取特定数量的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据我在properties文件中提供的设置来检索文件. 例如我只想在第一次迭代中获取50个文件,然后停止获取所有文件,因为文件夹中可能有成千上万个文件.

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.

我如何才能随机获得50个文件,而又不获取所有列表或遍历文件以获得50个文件?

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

编辑:我已经删除了for语句.即使我只提供了一个要从中获取的文件夹也可以获取所有文件,但counter变量仍然会遍历该文件夹中的所有文件,并不是一个好的解决方案.

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.

推荐答案

使用java.nio API中的FilesPath代替File.

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

您还可以在Java 8中将它们与Stream一起使用:

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


在Java 7中,您可以使用SimpleFileVisitor实现来停止文件移动,该实现应小心地终止与谓词匹配的50个文件:


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

以及如何使用它:

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

这篇关于如何从目录中获取特定数量的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆