简体   繁体   中英

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.

看一下File.lastModified函数和Date的函数来检查它是否在过去7天内。

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

you can try this, this will definitely help you,

your imports will be this only,

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

.......

public static void main(String[] args) {
    File f = new File("your-working-directory-path");

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH, -7);

    Date lastDate = calendar.getTime();

    System.out.println(lastDate);

    for(String file : f.list()){

        String filePath = f.getAbsolutePath() + File.separator + file;;

        File f1 = new File(filePath);

        long diffInDays = getDateDiff(lastDate,new Date(f1.lastModified()),TimeUnit.DAYS);

        if(Math.abs(diffInDays) <= 7){
            // do your stuff here...
        }
    }

}

public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
    long diffInMillies = date2.getTime() - date1.getTime();
    return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}

Use the lastModified() method of the File class. This will return you the last modification timestamp of that file and then you check whether this is within the last 7 days or not.

Give FileFilter a try.

    long weekAgo = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7);

    File directory = new File(target_dir);
    File[] files = directory.listFiles(pathname -> pathname.lastModified() >= weekAgo);

    for (File file : files) {
        // Your code
    }

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