[英]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 我在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 如果您要实际监视新创建的文件,则可以使用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. 如果仅查找其中的文件,则可以使用例如Apache Commons FileUtils类的方法列出在两个特定日期之间修改/创建的所有文件。
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. 可以使用file.listFiles()方法完成。
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 然后对于每个文件对象,使用file.lastModified()获取时间戳,然后检查它是否在您指定的时间戳之间
startTimestamp < file.lastModified() < endTimestamp startTimestamp <file.lastModified()<endTimestamp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.