我正在寻找一种有效的方法来迭代一个或多个目录中的数千个文件.
迭代目录中文件的唯一方法似乎是File.list*()
函数.这些函数有效地加载某种Collection中的整个文件列表,然后让用户迭代它.就时间/内存消耗而言,这似乎是不切实际的.我试着看看commons-io和其他类似的工具.但他们最终都File.list*()
在里面打电话.JDK7已walkFileTree()
接近尾声,但我无法控制何时选择下一个元素.
我在一个目录中有超过150,000个文件,经过多次-Xms/-Xmm试运行后,我摆脱了内存溢出问题.但是填充阵列所需的时间并没有改变.
我希望创建一些Iterable类,它使用opendir()/ closedir()函数来根据需要延迟加载文件名.有没有办法做到这一点?
更新:
Java 7 NIO.2通过java.nio.file.DirectoryStream支持文件迭代.这是一个Iterable类.至于JDK6及以下版本,唯一的选择是File.list*()
方法.
下面是如何迭代目录条目的示例,而无需将 159k 个目录条目存储在数组中。根据需要添加错误/异常/关闭/超时处理。该技术使用辅助线程来加载小型阻塞队列。
用法是:
FileWalker z = new FileWalker(new File("\\"), 1024); // start path, queue size
Iterator<Path> i = z.iterator();
while (i.hasNext()) {
Path p = i.next();
}
Run Code Online (Sandbox Code Playgroud)
这个例子:
public class FileWalker implements Iterator<Path> {
final BlockingQueue<Path> bq;
FileWalker(final File fileStart, final int size) throws Exception {
bq = new ArrayBlockingQueue<Path>(size);
Thread thread = new Thread(new Runnable() {
public void run() {
try {
Files.walkFileTree(fileStart.toPath(), new FileVisitor<Path>() {
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
try {
bq.offer(file, 4242, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return FileVisitResult.CONTINUE;
}
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.setDaemon(true);
thread.start();
thread.join(200);
}
public Iterator<Path> iterator() {
return this;
}
public boolean hasNext() {
boolean hasNext = false;
long dropDeadMS = System.currentTimeMillis() + 2000;
while (System.currentTimeMillis() < dropDeadMS) {
if (bq.peek() != null) {
hasNext = true;
break;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return hasNext;
}
public Path next() {
Path path = null;
try {
path = bq.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
return path;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
Run Code Online (Sandbox Code Playgroud)