简体   繁体   中英

How to list all newly created files in a specific directory?

What is the way to list files created, for example, between two timestamps? I'd like to list all newly created files and then move them to a different directory.

I'm working on Windows

public void afterDate() throws IOException {
    final String pathToDirectory = "/path/to/directory";
    final long afterDate = new Date().getTime();
    final List<Path> paths = new ArrayList<>();
    final Path directory = Paths.get(pathToDirectory);
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) {
        for (Path path : directoryStream) {
            final BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
            final long creationTime = attr.creationTime().toMillis();
            if (creationTime >= afterDate) {
                paths.add(path);
            }
        }
    }
    for (final Path path : paths) {
        System.out.println(path.getFileName());
    }

}

If you want to actually watch out actively for newly created files, you can use a WatchService: http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html

If you are only looking for the files that are there, you could, for example use the Apache Commons FileUtils class' methods to list all files modified/create between two specific dates.

The logic will be as below

Use a file class.

Iterate through all the files in the directory

It can be done using the file.listFiles() method.

The method will return all the files (files as well as directories) in the directory.

Then for each of the file object, get the timestamp using file.lastModified() and then check if it is between the timestamps you have specified

startTimestamp < file.lastModified() < endTimestamp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM