首页 > 解决方案 > 如何在 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");
    }   

}

标签: javamaven

解决方案


您想按日期对这些文件进行排序。该方法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--


推荐阅读