如何使用java列出目录中的N个文件 [英] How to list only N files in directory using java
问题描述
如果我有一个包含很多文件的目录(大约1000个文件)。其中一些文件名为 .processed ,而其他文件则没有。
If I have a directory contains a lot of files (about 1000 file). Some of these files named .processed and other not.
如何只列出10个未处理的文件。
How can I list only 10 unprocessed files.
我正在使用此代码过滤处理过的文件。
I am using this code to filter the processed file.
File[] inputFileList = inputDirectory.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return !pathname.getName().endsWith(".processed");
}
});
但是如果未处理文件的数量很大,这可能会导致内存错误。所以每次应用程序运行时我都需要读取有限数量的文件。
But if the number of un-processed files is huge, this may lead to memory error. so I need to read a limited number of files each time the application will run.
推荐答案
这就是你应该使用java的原因。 nio.file。使用Java 8:
Which is why you should use java.nio.file. Using Java 8:
final Path baseDir = Paths.get("path/to/dir");
final List<Path> tenFirstEntries;
final BiPredicate<Path, BasicFileAttributes> predicate = (path, attrs)
-> attrs.isRegularFile() && path.getFileName().endsWith(".processed");
try (
final Stream<Path> stream = Files.find(baseDir, 1, predicate);
) {
tenFirstEntries = stream.limit(10L).collect(Collectors.toList());
}
使用Java 7:
final Path baseDir = Paths.get("path/to/dir");
final List<Path> tenFirstEntries = new ArrayList<>(10);
final DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>()
{
@Override
public boolean accept(final Path entry)
{
return entry.getFileName().endsWith(".processed")
&& Files.isRegularFile(entry);
}
};
try (
final DirectoryStream<Path> stream
= Files.newDirectoryStream(baseDir, filter);
) {
final Iterator<Path> iterator = stream.iterator();
for (int i = 0; iterator.hasNext() && i < 10; i++)
tenFirstEntries.add(iterator.next());
}
与 File.listFiles()$ c不同$ c>,java.nio.file使用延迟填充的目录条目流。
Unlike File.listFiles()
, java.nio.file use lazily populated streams of directory entries.
抛弃的另一个原因文件
。毕竟这是2015年。
One more reason to ditch File
. This is 2015 after all.
这篇关于如何使用java列出目录中的N个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!