[英]How to read all files in directory iteratively in Java?
I have a directory on network drive with million of files. 我在网络驱动器上有一个包含数百万个文件的目录。 If I try to read it with 如果我尝试阅读
folder.listFiles()
it will take a lot of time until resulting array will be filled with files. 在结果数组中充满文件之前,将花费大量时间。
I would like to receive files by one and printout a progress. 我希望一个人接收文件并打印进度。
How can I do this in Java? 如何用Java做到这一点?
You might try with DirectoryStream
: 您可以尝试使用DirectoryStream
:
Path dir = Paths.get("C:\\"); // directory to list
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path entry: stream) {
System.out.println(entry);
}
} catch (DirectoryIteratorException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
You can also make the DirectoryStream
filter files for you if you need to: all you need to do is add a parameter to the Files.newDirectoryStream
call: 如果需要,还可以为DirectoryStream
筛选文件:您需要做的就是向Files.newDirectoryStream
调用添加一个参数:
DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{txt,png,jpg}");
You can use the NIO.2 API: 您可以使用NIO.2 API:
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get("/path/to/directory"))) {
for (Path path : directoryStream) {
System.out.println(path.toString());
}
} catch (IOException ex) {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.