Java删除超过N天的文件

发布于 2024-11-27 03:47:13 字数 1172 浏览 1 评论 0原文

我想要一些 Java 代码来删除超过 N 天的文件。

这是我的尝试,但效果不太好。

public void deleteFilesOlderThanNdays(final int daysBack, final String dirWay) {

    System.out.println(dirWay);
    System.out.println(daysBack);

    final File directory = new File(dirWay);
    if(directory.exists()){
        System.out.println(" Directory Exists");
        final File[] listFiles = directory.listFiles();          
        final long purgeTime = 
            System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);

        System.out.println("System.currentTimeMillis " + 
            System.currentTimeMillis());

        System.out.println("purgeTime " + purgeTime);

        for(File listFile : listFiles) {
            System.out.println("Length : "+ listFiles.length);
            System.out.println("listFile.getName() : " +listFile.getName());
            System.out.println("listFile.lastModified() :"+
                listFile.lastModified());

            if(listFile.lastModified() < purgeTime) {
                System.out.println("Inside File Delete");
            }
        }
    } 
    else 
    {
    }
}

是否有一些简单的代码可以删除目录中超过 N 天的文件?

I would like some Java code to Delete files older than N days.

Here is my attempt, but it doesn't work quite right.

public void deleteFilesOlderThanNdays(final int daysBack, final String dirWay) {

    System.out.println(dirWay);
    System.out.println(daysBack);

    final File directory = new File(dirWay);
    if(directory.exists()){
        System.out.println(" Directory Exists");
        final File[] listFiles = directory.listFiles();          
        final long purgeTime = 
            System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);

        System.out.println("System.currentTimeMillis " + 
            System.currentTimeMillis());

        System.out.println("purgeTime " + purgeTime);

        for(File listFile : listFiles) {
            System.out.println("Length : "+ listFiles.length);
            System.out.println("listFile.getName() : " +listFile.getName());
            System.out.println("listFile.lastModified() :"+
                listFile.lastModified());

            if(listFile.lastModified() < purgeTime) {
                System.out.println("Inside File Delete");
            }
        }
    } 
    else 
    {
    }
}

Is there some simple code to delete files older than N days in a directory?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

箹锭⒈辈孓 2024-12-04 03:47:13

尝试使用 Calendar-Class相反:

 Calendar cal = Calendar.getInstance();  
 cal.add(Calendar.DAY_OF_MONTH, daysBack * -1);  
 long purgeTime = cal.getTimeInMillis();   

或者尝试此解决方案

您的天数是否超过24?如果是这样,则存在溢出问题。

如果天数为 25,则该值为:

25 * 24 * 60 * 60 * 1000

数学值为 2160000000。但是,该值大于 Integer.MAX_VALUE,因此该值会溢出到
<代码>-12516353。因此,清除时间将在未来,并且永远不会满足。大于25的值只会使问题变得更糟;甚至有可能溢出非常严重,以至于乘法结果再次产生正值,从而可能清除所有文件。

解决方法很简单:

  1. daysBack 声明为 long
  2. daysBack 转换为 long

    long purgeTime = System.currentTimeMillis() - ((long)daysBack * 24 * 60 * 60 * 1000);  
    
  3. 在计算中使用显式长文本:

    long purgeTime = System.currentTimeMillis() - (daysBack * 24L * 60L * 60L * 1000L); 
    

对于所有三个解决方案,第一个和/或第二个操作数是 long 的事实会将整个结果变成 long,允许值为 2160000000 没有溢出。

Try to use the Calendar-Class instead:

 Calendar cal = Calendar.getInstance();  
 cal.add(Calendar.DAY_OF_MONTH, daysBack * -1);  
 long purgeTime = cal.getTimeInMillis();   

Or try this solution:

Is your number of days over 24? If so, you have an overflow problem.

If the number of days is 25, the value will be:

25 * 24 * 60 * 60 * 1000

The mathematical value is 2160000000. However, this is larger than Integer.MAX_VALUE, and therefore the value overflows to
-12516353. As a result, the purge time will be in the future, and will never be met. Values larger than 25 will only make the problem worse; it's even possible the overflow is so bad that the multiplication results in a positive value again leading to perhaps purge all files.

The fix is easy:

  1. declare daysBack as a long
  2. cast daysBack to a long

    long purgeTime = System.currentTimeMillis() - ((long)daysBack * 24 * 60 * 60 * 1000);  
    
  3. Use explicit long literals inside the calculation:

    long purgeTime = System.currentTimeMillis() - (daysBack * 24L * 60L * 60L * 1000L); 
    

For all three solutions, the fact that the first and/or second operand is a long turns the entire result into a long, allowing a value of 2160000000 without overflowing.

紫﹏色ふ单纯 2024-12-04 03:47:13

我使用这个简单的代码片段来删除超过 N 天的文件

在此代码片段中,删除是基于文件上次修改的日期时间

daysBack = 删除超过 N 天的文件
dirWay = 包含文件的目录

public static void deleteFilesOlderThanNdays(int daysBack, String dirWay) {

File directory = new File(dirWay);
if(directory.exists()){

    File[] listFiles = directory.listFiles();           
    long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);
    for(File listFile : listFiles) {
        if(listFile.lastModified() < purgeTime) {
            if(!listFile.delete()) {
                System.err.println("Unable to delete file: " + listFile);
            }
         }
      }
   }
}

谢谢

I use this simple code snippet to delete files older than N days

In this snippet deletion is based on file last-modified datetime

daysBack = Delete files older than N days
dirWay = Directory that contain files

public static void deleteFilesOlderThanNdays(int daysBack, String dirWay) {

File directory = new File(dirWay);
if(directory.exists()){

    File[] listFiles = directory.listFiles();           
    long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);
    for(File listFile : listFiles) {
        if(listFile.lastModified() < purgeTime) {
            if(!listFile.delete()) {
                System.err.println("Unable to delete file: " + listFile);
            }
         }
      }
   }
}

Thanks

流绪微梦 2024-12-04 03:47:13

Java程序删除超过N天的目录中的文件:

我对你不小心用这个删除你的硬盘计算机不负有责任。除非您了解它的作用和原因,否则不要运行它。如果您不小心针对根目录或某些敏感目录运行此文件,旧文件将被永久删除。

该 Java 程序将收集 C:\Users\penguins 中所有文件的列表,这些文件的名称中包含文本:MyLogFile_。它查看每个文件的 lastModified() 日期,并查看它的存在时间(以毫秒为单位),如果差异大于指定的天数(8 天,以毫秒为单位),则该文件为已删除。

import java.io.File;
import java.util.*;

class Runner{
    public static void main(String[] args){

        long numDays = 8;   //this needs to be a long.

        //WARNING!  OLD FILES IN THIS DIRECTORY WILL BE DELETED.
        String dir = "C:\\Users\\penguins";
        //IF YOU ACCIDENTALLY POINT THIS TO C:\\Windows or other sensitive
        //directory (and run it) you will be living in the house of pain.

        File directory = new File(dir);
        File[] fList = directory.listFiles();

        if (fList != null){
            for (File file : fList){
                if (file.isFile() &&
                    file.getName().contains("MyLogFile_")){

                    long diff = new Date().getTime() - file.lastModified();
                    long cutoff = (numDays * (24 * 60 * 60 * 1000));

                    if (diff > cutoff) {
                      file.delete();
                    }
                }
            }
        }
    }
}

要让此代码为您工作,您需要:

  1. 将 dir 设置为您要从中删除文件的目录。
  2. 将 numDays 变量设置为文件被删除的天数。
  3. MyLogFile_ 字设置为要删除的文件的签名。将其设置为空白以查看所有文件。

当此代码失败时:

如果系统日期更改为未来或过去(或发生一些奇怪的闰秒、时区更改或系统日期编辑),那么这可能会继续删除横冲直撞。如果文件上的日期被人为操纵,那么这可能会导致删除狂潮。如果文件的权限限制过多,则该文件将不会被删除。

Java program to delete files in a directory older than N days:

I am not responsible for you accidentally erasing your hard drive computer with this. Don't run it unless you understand what it does and why it does it. If you accidentally run this file against root, or some sensitive directory, old files will be permanently erased.

This Java program will gather a list of all the files in C:\Users\penguins that contain the text: MyLogFile_ in its name. It looks at the lastModified() date of each file, and sees how old it is in milliseconds, if the difference is greater than the number of days specified (8 days in milliseconds), then the file is deleted.

import java.io.File;
import java.util.*;

class Runner{
    public static void main(String[] args){

        long numDays = 8;   //this needs to be a long.

        //WARNING!  OLD FILES IN THIS DIRECTORY WILL BE DELETED.
        String dir = "C:\\Users\\penguins";
        //IF YOU ACCIDENTALLY POINT THIS TO C:\\Windows or other sensitive
        //directory (and run it) you will be living in the house of pain.

        File directory = new File(dir);
        File[] fList = directory.listFiles();

        if (fList != null){
            for (File file : fList){
                if (file.isFile() &&
                    file.getName().contains("MyLogFile_")){

                    long diff = new Date().getTime() - file.lastModified();
                    long cutoff = (numDays * (24 * 60 * 60 * 1000));

                    if (diff > cutoff) {
                      file.delete();
                    }
                }
            }
        }
    }
}

To get this code to work for you, you need to:

  1. Set the dir to the directory you want to delete files from.
  2. set the numDays variable to the number of days past which files get deleted.
  3. Set the MyLogFile_ word to the signature of files you want to delete. Set it to blank to look at all files.

When this code will fail you:

If the system Date is changed to future or past, (or some weird leap-second, timezone change, or system date edit) happens, then this may go on a deleting rampage. If dates on the files are artificially manipulated, then this may go on a deleting rampage. If permissions are too restrictive on the files, the file won't be deleted.

山色无中 2024-12-04 03:47:13

如果您的意思是“大约 30 天前”,则其他答案是正确的。但如果你想更精确,那么你应该注意时区。如果您指的是一整天,请注意一天中的时间。

如果您想使用UTC/GMT,请使用此时区对象:DateTimeZone.UTC

以下是使用 Joda-Time 3.2 库的一些示例代码。

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Oslo" );

DateTime now = new DateTime( timeZone );
DateTime cutoff = now.minusDays( 30 ).withTimeAtStartOfDay();

DateTime fileCreationDateTime = new DateTime( 2014, 1, 2, 3, 4, 5, timeZone );
boolean fileShouldBeDeleted = fileCreationDateTime.isBefore( cutoff );

DateTime file2CreationDateTime = now.minusMinutes( 1 );
boolean file2ShouldBeDeleted = file2CreationDateTime.isBefore( cutoff );

转储到控制台...

System.out.println( "now: " + now );
System.out.println( "cutoff: " + cutoff );
System.out.println( "fileCreationDateTime: " + fileCreationDateTime );
System.out.println( "fileShouldBeDeleted: " + fileShouldBeDeleted );
System.out.println( "file2CreationDateTime: " + file2CreationDateTime );
System.out.println( "file2ShouldBeDeleted: " + file2ShouldBeDeleted );

运行时...

now: 2014-02-07T07:20:32.898+01:00
cutoff: 2014-01-08T00:00:00.000+01:00
fileCreationDateTime: 2014-01-02T03:04:05.000+01:00
fileShouldBeDeleted: true
file2CreationDateTime: 2014-02-07T07:19:32.898+01:00
file2ShouldBeDeleted: false

If you mean "approximately 30 days ago", the other answers are correct. But if you mean to be more precise, then you should pay attention to time zone. And if you mean whole days, pay attention to time-of-day.

If you want to use UTC/GMT, use this time zone object: DateTimeZone.UTC

Here is some example code using the Joda-Time 3.2 library.

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Oslo" );

DateTime now = new DateTime( timeZone );
DateTime cutoff = now.minusDays( 30 ).withTimeAtStartOfDay();

DateTime fileCreationDateTime = new DateTime( 2014, 1, 2, 3, 4, 5, timeZone );
boolean fileShouldBeDeleted = fileCreationDateTime.isBefore( cutoff );

DateTime file2CreationDateTime = now.minusMinutes( 1 );
boolean file2ShouldBeDeleted = file2CreationDateTime.isBefore( cutoff );

Dump to console…

System.out.println( "now: " + now );
System.out.println( "cutoff: " + cutoff );
System.out.println( "fileCreationDateTime: " + fileCreationDateTime );
System.out.println( "fileShouldBeDeleted: " + fileShouldBeDeleted );
System.out.println( "file2CreationDateTime: " + file2CreationDateTime );
System.out.println( "file2ShouldBeDeleted: " + file2ShouldBeDeleted );

When run…

now: 2014-02-07T07:20:32.898+01:00
cutoff: 2014-01-08T00:00:00.000+01:00
fileCreationDateTime: 2014-01-02T03:04:05.000+01:00
fileShouldBeDeleted: true
file2CreationDateTime: 2014-02-07T07:19:32.898+01:00
file2ShouldBeDeleted: false
慈悲佛祖 2024-12-04 03:47:13

您可以使用 file.lastModified() 方法,

如下所示。

文件 file = new File("YOUR_FOLDER_PATH");

long diff = new Date().getTime() - file.lastModified();

 if (diff > Z * 24 * 60 * 60 * 1000) {
  file.delete();
 }

You can use file.lastModified() method

Some thing like below.

File file = new File("YOUR_FOLDER_PATH");

long diff = new Date().getTime() - file.lastModified();

 if (diff > Z * 24 * 60 * 60 * 1000) {
  file.delete();
 }
尐籹人 2024-12-04 03:47:13

使用 Java 8 的代码片段

    public static void deleteFilesOlderThanNdays(int daysAgo, String destDir) throws IOException {

    Instant instantDaysAgo = Instant.from(ZonedDateTime.now().minusDays(daysAgo));

    BiPredicate<Path, BasicFileAttributes> fileIsOlderThanNDays = 
            (path, attr) ->  attr.lastModifiedTime().compareTo( FileTime.from(instantDaysAgo)) < 0 ;


    List<Path> filesToDelete = (List) Files.find(Paths.get(destDir), 1 , fileIsOlderThanNDays )
                                            .collect(Collectors.toList());


    for (Path path : filesToDelete) {
            Files.delete(path);
        }
}

A code snippet using Java 8

    public static void deleteFilesOlderThanNdays(int daysAgo, String destDir) throws IOException {

    Instant instantDaysAgo = Instant.from(ZonedDateTime.now().minusDays(daysAgo));

    BiPredicate<Path, BasicFileAttributes> fileIsOlderThanNDays = 
            (path, attr) ->  attr.lastModifiedTime().compareTo( FileTime.from(instantDaysAgo)) < 0 ;


    List<Path> filesToDelete = (List) Files.find(Paths.get(destDir), 1 , fileIsOlderThanNDays )
                                            .collect(Collectors.toList());


    for (Path path : filesToDelete) {
            Files.delete(path);
        }
}
爱殇璃 2024-12-04 03:47:13

我正在研究类似的东西,并且包装了一些 java.nio.file.Files 方法,以便拥有一个干净的基于 Java 8 流的方法。

我的需求是 7 天,但您可以根据您的需要进行调整:

public void cleanFilesOlderThan7Days() {
    try {
        Files.walk(Paths.get("temp/raw_reports"))
                .filter(Files::isRegularFile)
                .filter(FilesUtils::isOlderThan7Days)
                .forEach(FilesUtils::delete);
    } catch (IOException e) {
        log.error("Could not clean old files", e);
    }
}

我将包装的方法放入 utils 类中:

public class FilesUtils {

@SneakyThrows
public static boolean isOlderThan7Days(java.nio.file.Path path) {
    FileTime lastModifiedTime = Files.getLastModifiedTime(path);
    Duration interval = Duration.between(lastModifiedTime.toInstant(), Instant.now());
    return interval.toDays() > 7;
}

@SneakyThrows
public static void delete(java.nio.file.Path path) {
    Files.delete(path);
}

}

请注意,我使用的是 Lombok 插件中的 @SneakyThrows。如果您不使用它,您可以实现它或使用 try/catch 来威胁异常。

I was researching something similar and I've wrapped some java.nio.file.Files methods in order to have a clean Java 8 stream based method.

My need was for 7 days period but you can adapt it to your need:

public void cleanFilesOlderThan7Days() {
    try {
        Files.walk(Paths.get("temp/raw_reports"))
                .filter(Files::isRegularFile)
                .filter(FilesUtils::isOlderThan7Days)
                .forEach(FilesUtils::delete);
    } catch (IOException e) {
        log.error("Could not clean old files", e);
    }
}

I put the wrapped methods in an utils class:

public class FilesUtils {

@SneakyThrows
public static boolean isOlderThan7Days(java.nio.file.Path path) {
    FileTime lastModifiedTime = Files.getLastModifiedTime(path);
    Duration interval = Duration.between(lastModifiedTime.toInstant(), Instant.now());
    return interval.toDays() > 7;
}

@SneakyThrows
public static void delete(java.nio.file.Path path) {
    Files.delete(path);
}

}

Notice I am using @SneakyThrows from Lombok plugin. If you are not using it you can either implement it or use try/catch to threat the exceptions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文