I want to get the files which are modified in last 7 days using Java. Once I get the files I need it for other file operations.
Right now I am able to get all files from the directory and perform my file operations. Please suggest me how to get the files which are modified in last 7 days.
Below is the code which I used to get the files from the directory and do the file operations.
String target_dir = "D:/Reports/Project";
File dir = new File(target_dir);
File[] files = dir.listFiles();
int count = 0;
for (File f : files) {
if(f.isFile()) {
BufferedReader inputStream = null;
FileReader in = null;
try {
// Working Code
}catch (Exception e) {
System.out.println("Error while retreiving files ");
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
Please suggest. Thanks in Advance.
public static void main(String[] args) throws IOException {
String dir = "myDirectory";
// cutoff date:
Instant lastWeek = Instant.now().minus(7, ChronoUnit.DAYS);
// find with filter
Files.find(Paths.get(dir), Integer.MAX_VALUE,
(p, a) -> {
try {
return Files.isRegularFile(p)
&& Files.getLastModifiedTime(p).toInstant().isAfter(lastWeek);
}
catch(IOException e) {
throw new RuntimeException(e);
}
})
.forEach(System.out::println);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With