Marcus
Marcus

Reputation: 3869

how to sort files during processing in Java

I am quiet new to Java and during processing i found that the files has been processed randomly without any order.

I want to sort the files by date such that it can process sequencly. There has been few functions in java which can does that but dont know exactly where i need to place it.

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");
    }   

}

Upvotes: 1

Views: 2226

Answers (2)

Harshit Vadodaria
Harshit Vadodaria

Reputation: 76

The method Files.walk returns a Stream of Path (refer Docs), and you can call the 'sorted' method, implementing your own comparator, which lets you sort the stream based on any attribute you want.

You can do something like this if you want to sort the files by creation date:

Files.walk(indir, 1, FileVisitOption.FOLLOW_LINKS)
 .sorted(
        new Comparator<Path>() {
            public int compare(Path p1, Path p2) {
                return Files.readAttributes(p1, BasicFileAttributes.class).creationTime().toMillis() -
                            Files.readAttributes(p2, BasicFileAttributes.class).creationTime().toMillis();
            }
        }
     )
    .filter(Files::isRegularFile)
    .filter(f -> f.getFileName().toString().matches("OFFENE_LIEFERORDERS.*\\.csv"))
    .forEachOrdered(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);
        }
    });

This uses the java.nio.file.attribute.BasicFileAttributes class, so you should import this at the top of your file.

Upvotes: 2

Nordiii
Nordiii

Reputation: 466

You want to sort those Files by date. The method Files.walk() will return Stream<Path> and it will be sorted by the name and not the date, it doesn't even have the date as the values are paths. You can use the .sorted() method with a comparator to sort after last modified:

            Files.walk(indir, 1, FileVisitOption.FOLLOW_LINKS)
                .sorted(Comparator.comparingLong(p -> p.toFile().lastModified()))
                .forEachOrdered(System.out::println);

This uses the Comparator class to compare the long value returned by .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--

Upvotes: 3

Related Questions