use*_*929 37 java time delete-file
如何找出使用java创建文件的时间,因为我希望删除早于某个时间段的文件,目前我正在删除目录中的所有文件,但这并不理想:
public void DeleteFiles() {
File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
System.out.println("Called deleteFiles");
DeleteFiles(file);
File file2 = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/Uploaded/");
DeleteFilesNonPdf(file2);
}
public void DeleteFiles(File file) {
System.out.println("Now will search folders and delete files,");
if (file.isDirectory()) {
for (File f : file.listFiles()) {
DeleteFiles(f);
}
} else {
file.delete();
}
}
Run Code Online (Sandbox Code Playgroud)
以上是我当前的代码,我现在正在尝试添加一个if语句,只删除比一周更早的文件.
编辑:
@ViewScoped
@ManagedBean
public class Delete {
public void DeleteFiles() {
File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
System.out.println("Called deleteFiles");
DeleteFiles(file);
File file2 = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/Uploaded/");
DeleteFilesNonPdf(file2);
}
public void DeleteFiles(File file) {
System.out.println("Now will search folders and delete files,");
if (file.isDirectory()) {
System.out.println("Date Modified : " + file.lastModified());
for (File f : file.listFiles()) {
DeleteFiles(f);
}
} else {
file.delete();
}
}
Run Code Online (Sandbox Code Playgroud)
现在添加一个循环.
编辑
我注意到在测试上面的代码时,我得到了最后一次修改:
INFO: Date Modified : 1361635382096
Run Code Online (Sandbox Code Playgroud)
我应该如何编写if循环来说明它是否超过7天,当它是上述格式时删除它?
Nis*_*hth 44
您可以使用它File.lastModified()
来获取文件/目录的上次修改时间.
可以像这样使用:
long diff = new Date().getTime() - file.lastModified();
if (diff > x * 24 * 60 * 60 * 1000) {
file.delete();
}
Run Code Online (Sandbox Code Playgroud)
删除超过x
(一int
)天的文件.
Rya*_*art 30
Commons IO内置支持使用AgeFileFilter按年龄过滤文件.你DeleteFiles
可以看起来像这样:
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.AgeFileFilter;
import static org.apache.commons.io.filefilter.TrueFileFilter.TRUE;
// a Date defined somewhere for the cutoff date
Date thresholdDate = <the oldest age you want to keep>;
public void DeleteFiles(File file) {
Iterator<File> filesToDelete =
FileUtils.iterateFiles(file, new AgeFileFilter(thresholdDate), TRUE);
for (File aFile : filesToDelete) {
aFile.delete();
}
}
Run Code Online (Sandbox Code Playgroud)
更新:要使用编辑中给出的值,请将以下内容定义thresholdDate
为:
Date tresholdDate = new Date(1361635382096L);
Run Code Online (Sandbox Code Playgroud)
Mat*_*ttC 12
使用Apache utils可能是最简单的.这是我能提出的最简单的解决方案.
public void deleteOldFiles() {
Date oldestAllowedFileDate = DateUtils.addDays(new Date(), -3); //minus days from current date
File targetDir = new File("C:\\TEMP\\archive\\");
Iterator<File> filesToDelete = FileUtils.iterateFiles(targetDir, new AgeFileFilter(oldestAllowedFileDate), null);
//if deleting subdirs, replace null above with TrueFileFilter.INSTANCE
while (filesToDelete.hasNext()) {
FileUtils.deleteQuietly(filesToDelete.next());
} //I don't want an exception if a file is not deleted. Otherwise use filesToDelete.next().delete() in a try/catch
}
Run Code Online (Sandbox Code Playgroud)
Mad*_*mer 12
LocalDate today = LocalDate.now();
LocalDate eailer = today.minusDays(30);
Date threshold = Date.from(eailer.atStartOfDay(ZoneId.systemDefault()).toInstant());
AgeFileFilter filter = new AgeFileFilter(threshold);
File path = new File("...");
File[] oldFolders = FileFilterUtils.filter(filter, path);
for (File folder : oldFolders) {
System.out.println(folder);
}
Run Code Online (Sandbox Code Playgroud)
非递归选项,用于删除当前文件夹中超过N天的所有文件(忽略子文件夹):
public static void deleteFilesOlderThanNDays(int days, String dirPath) throws IOException {
long cutOff = System.currentTimeMillis() - (days * 24 * 60 * 60 * 1000);
Files.list(Paths.get(dirPath))
.filter(path -> {
try {
return Files.isRegularFile(path) && Files.getLastModifiedTime(path).to(TimeUnit.MILLISECONDS) < cutOff;
} catch (IOException ex) {
// log here and move on
return false;
}
})
.forEach(path -> {
try {
Files.delete(path);
} catch (IOException ex) {
// log here and move on
}
});
}
Run Code Online (Sandbox Code Playgroud)
递归选项,它遍历子文件夹并删除所有早于N天的文件:
public static void recursiveDeleteFilesOlderThanNDays(int days, String dirPath) throws IOException {
long cutOff = System.currentTimeMillis() - (days * 24 * 60 * 60 * 1000);
Files.list(Paths.get(dirPath))
.forEach(path -> {
if (Files.isDirectory(path)) {
try {
recursiveDeleteFilesOlderThanNDays(days, path.toString());
} catch (IOException e) {
// log here and move on
}
} else {
try {
if (Files.getLastModifiedTime(path).to(TimeUnit.MILLISECONDS) < cutOff) {
Files.delete(path);
}
} catch (IOException ex) {
// log here and move on
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
对于使用NIO文件流和JSR-310的JDK 8解决方案
long cut = LocalDateTime.now().minusWeeks(1).toEpochSecond(ZoneOffset.UTC);
Path path = Paths.get("/path/to/delete");
Files.list(path)
.filter(n -> {
try {
return Files.getLastModifiedTime(n)
.to(TimeUnit.SECONDS) < cut;
} catch (IOException ex) {
//handle exception
return false;
}
})
.forEach(n -> {
try {
Files.delete(n);
} catch (IOException ex) {
//handle exception
}
});
Run Code Online (Sandbox Code Playgroud)
这里很糟糕的是需要处理每个lambda中的异常.API UncheckedIOException
对每个IO方法都有重载会很棒.帮助者可以这样写:
public static void main(String[] args) throws IOException {
long cut = LocalDateTime.now().minusWeeks(1).toEpochSecond(ZoneOffset.UTC);
Path path = Paths.get("/path/to/delete");
Files.list(path)
.filter(n -> Files2.getLastModifiedTimeUnchecked(n)
.to(TimeUnit.SECONDS) < cut)
.forEach(n -> {
System.out.println(n);
Files2.delete(n, (t, u)
-> System.err.format("Couldn't delete %s%n",
t, u.getMessage())
);
});
}
private static final class Files2 {
public static FileTime getLastModifiedTimeUnchecked(Path path,
LinkOption... options)
throws UncheckedIOException {
try {
return Files.getLastModifiedTime(path, options);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
public static void delete(Path path, BiConsumer<Path, Exception> e) {
try {
Files.delete(path);
} catch (IOException ex) {
e.accept(path, ex);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是使用Time API的Java 8版本。它已在我们的项目中经过测试和使用:
public static int deleteFiles(final Path destination,
final Integer daysToKeep) throws IOException {
final Instant retentionFilePeriod = ZonedDateTime.now()
.minusDays(daysToKeep).toInstant();
final AtomicInteger countDeletedFiles = new AtomicInteger();
Files.find(destination, 1,
(path, basicFileAttrs) -> basicFileAttrs.lastModifiedTime()
.toInstant().isBefore(retentionFilePeriod))
.forEach(fileToDelete -> {
try {
if (!Files.isDirectory(fileToDelete)) {
Files.delete(fileToDelete);
countDeletedFiles.incrementAndGet();
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
return countDeletedFiles.get();
}
Run Code Online (Sandbox Code Playgroud)
JavaSE 规范解决方案。删除超过expirationPeriod
几天的文件。
private void cleanUpOldFiles(String folderPath, int expirationPeriod) {
File targetDir = new File(folderPath);
if (!targetDir.exists()) {
throw new RuntimeException(String.format("Log files directory '%s' " +
"does not exist in the environment", folderPath));
}
File[] files = targetDir.listFiles();
for (File file : files) {
long diff = new Date().getTime() - file.lastModified();
// Granularity = DAYS;
long desiredLifespan = TimeUnit.DAYS.toMillis(expirationPeriod);
if (diff > desiredLifespan) {
file.delete();
}
}
}
Run Code Online (Sandbox Code Playgroud)
例如 - 要删除文件夹“/sftp/logs”中超过 30 天的所有文件,请调用:
cleanUpOldFiles("/sftp/logs", 30);
归档时间: |
|
查看次数: |
55027 次 |
最近记录: |