package com.avaya.deletelogs;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.List;
public class DeleteLogs {
private String baseDir = "/opt/java/IVRLog";
private int daysBack = 4;
public void invokeProcess() {
getFolders();
}
public void getFolders() {
try {
File file = new File(baseDir);
String[] directories = file.list(new FilenameFilter() {
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
deleteFiles(daysBack, baseDir, Arrays.asList(directories));
} catch (Exception e) {
System.out.println(e);
}
}
public void deleteFiles(int daysBack, String dirWay, List< string> directories) {
for (String dir : directories) {
deleteFilesOlderThanNdays(daysBack, dir);
}
}
public void deleteFilesOlderThanNdays(int daysBack, String dirWay) {
File directory = new File(baseDir + "/" + dirWay);
if (directory.exists()) {
File[] listFiles = directory.listFiles();
long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);
for (File listFile : listFiles) {
try {
if (listFile.isFile()) {
if (listFile.lastModified() < purgeTime) {
if (!listFile.delete()) {
System.err.println("Unable to delete file: " + listFile);
}
}
} else {
continue;
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}
}
How to delete log4j/log file older than N number of days?
About Akram
Hi, I am a Software Engineer and working from last 7 years. I am not a professional blogger, just sharing my knowledge with you.
Java
Labels:
Interview Questions,
Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment