java 删除n天前的文件_java 删除N天前数据

public static void main(String[] args) {

File dir = new File("c:/test");

String matchName = "test.*\\.txt";

int keepDays = 5;

boolean recursive = true;

removeOldFile(dir, recursive, matchName, keepDays);

}

private static void removeOldFile(File dir, boolean recursive, String matchName,

int keepDays) {

DecimalFormat df = new DecimalFormat("0.00");

String[] extensions = null;

Collection files = FileUtils.listFiles(dir, extensions, recursive);

long currentTime = System.currentTimeMillis();

for (File f : files) {

String oneFileName = f.getName();

//System.out.println(oneFileName + ":" + oneFileName.matches(matchName));

if(oneFileName.matches(matchName)) {

long fileLastModified = f.lastModified();

long timeGap = currentTime - fileLastModified;

System.out.println("timeGap for file:" + f.getAbsolutePath() + " is " + df.format(timeGap / 1000.0 / 24 / 3600) + " day");

if(timeGap > keepDays * 24L * 3600 * 1000) {

System.out.println("begin to delete file:" + f.getAbsolutePath());

if(!f.delete()) {

throw new RuntimeException("delete file failed:" + f.getAbsolutePath());

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值