【发布时间】:2019-04-06 17:04:53
【问题描述】:
我有一个包含许多文件的目录,想要过滤具有特定名称的文件并将它们保存在fileList ArrayList 中,它以这种方式工作,但需要很多时间。有没有办法让它更快?
String processingDir = "C:/Users/Ferid/Desktop/20181024";
String CorrId = "00a3d321-171c-484a-ad7c-74e22ffa3625");
Path dirPath = Paths.get(processingDir);
ArrayList<Path> fileList;
try (Stream<Path> paths = Files.walk(dirPath))
{
fileList = paths.filter(t -> (t.getFileName().toString().indexOf("EPX_" +
corrId + "_") >= 0)).collect(Collectors.toCollection(ArrayList::new));
}
在尝试条件下遍历目录不需要太多时间,但在fileList 中收集它需要很多时间,我不知道究竟是哪个操作性能如此差或需要改进哪些操作. (这当然不是完整的代码,只是相关的东西)
【问题讨论】:
-
为什么你认为收藏是昂贵的部分?请注意,您要求流执行的所有操作(例如
filter、map等)通常仅在调用终止方法时执行,collect就是。 -
我已经测试过了,那行
fileList = paths.filter(t -> (t.getFileName().toString().indexOf("EPX_" + corrId + "_") >= 0)).collect(Collectors.toCollection(ArrayList::new));是花了很多时间的那一行 -
看看能不能转成并行流。