Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all files modified in last 7 days in a directory in Java

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.

like image 942
Krishna Avatar asked Mar 17 '16 13:03

Krishna


1 Answers

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);
}
like image 193
mtj Avatar answered Oct 02 '22 21:10

mtj