java - 如何在 Java 处理过程中对文件进行排序
问题描述
我对 Java 很陌生,在处理过程中我发现文件是随机处理的,没有任何顺序。
我想按日期对文件进行排序,以便它可以按顺序处理。java中很少有函数可以做到这一点,但不知道我需要把它放在哪里。
public class OMapping extends AbstractWorkflow {
private final static Logger LOG = LoggerFactory.getLogger(OMapping.class);
private WorkflowEnvironment workflowEnvironment;
@Override
public boolean run(CommandLine commandLine) throws Exception {
AnnotationConfigApplicationContext applicationContext = initializeApplicationContext();
String in = commandLine.getOptionValue("in");
String done = commandLine.getOptionValue("doneDir");
if (in == null) {
LOG.error("The input directory has not been specified");
return false;
}
if(done == null){
LOG.error("The done directory has not been specified");
return false;
}
Path indir = Paths.get(in);
Path doneDir = Paths.get(done);
MappingFileImporter oMappingFileImporter = applicationContext.getBean(oMappingFileImporter.class);
LOG.info("Importing files from " + in);
Files.walk(indir, 1, FileVisitOption.FOLLOW_LINKS)
.filter(Files::isRegularFile)
.filter(f -> f.getFileName().toString().matches("OFFENE_LIEFERORDERS.*\\.csv"))
.forEach(f -> {
try {
oMappingFileImporter.importFile(f);
Path moved = Files.move(f.toAbsolutePath(), doneDir.resolve(f.getFileName()), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
});
return true;
}
@Override
public String getName() {
return "orderidmappingimporter";
}
@Override
public void addOptions(Options options) {
options.addOption(null, "in", true,
"(orderidmappingimporter) specifies the input directory");
options.addOption(null, "doneDir", true,
"(orderidmappingimporter) specifies the done directory");
}
}
解决方案
您想按日期对这些文件进行排序。该方法Files.walk()
将返回Stream<Path>
,它将按名称而不是日期排序,它甚至没有日期,因为值是路径。您可以使用.sorted()
带有比较器的方法在上次修改后进行排序:
Files.walk(indir, 1, FileVisitOption.FOLLOW_LINKS)
.sorted(Comparator.comparingLong(p -> p.toFile().lastModified()))
.forEachOrdered(System.out::println);
这使用 Comparator 类来比较返回的 long 值.lastModified()
。
https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted--
推荐阅读
- javascript - 使用 x-spreadsheet 保留 excel 电子表格样式
- r - 如何根据两个分类变量和一个数值变量比较 R 数据框中变量之间的相似性
- jquery - jquery中的map()方法,如何按字母顺序排列
- flutter - 无法转换地图
在颤动中串起 - javascript - 为什么 VS Code 为数组项道具显示错误的 JSDoc?
- r - 从 R 中的 lm() 获取 F 和 p 值
- android - Android Studio 中支持印地语的大纲字体
- swiftui - 建模 JSON 货币对象
- python - 获取 SyntaxError:无效的语法,没有 pygame 的原因
- python - Celery 显示 django 的 runserver 日志而不是 celery 日志