I wrote this code for a 2001 server, running java 1.3. It deletes folders and files but not the main folder. Which is intended.
import java.io.File;
import java.security.InvalidParameterException;
import java.util.Date;
public class MainCopy {
String path;
int numDays;
File rootFolder;
public MainCopy(String path, int numDays) {
this.path = path;
this.numDays = numDays;
this.rootFolder = new File(path);
}
public void deleteFile(File delFile) {
if (delFile.isDirectory()) {
File[] files = delFile.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFile(files[i]);
}
if(delFile.list().length==0){
if (!delFile.equals(rootFolder)) {
delFile.delete();
System.out.println("Deleted: "
+ delFile.getAbsolutePath());
}
}
}else{
long diff = new Date().getTime() - delFile.lastModified();
if (diff >= numDays * 24 * 60 * 60 * 1000) {
delFile.delete();
System.out.println("Deleted: "
+ delFile.getAbsolutePath());
}
}
}
public static void main(String[] args) throws Exception {
String path;
String numDays;
if (args.length == 0) {
throw new InvalidParameterException("Arguments can not be empty. \n"
+ "Expected arguments are <PATH> <Deletion cut off>");
} else if (args.length == 2) {
path = args[0];
numDays = args[1];
File dir = new File(path);
int num;
try {
num = Integer.parseInt(numDays);
} catch (NumberFormatException e) {
throw new InvalidParameterException("Delete cut off must be a number");
}
if ((dir.exists() && dir.isDirectory()) && (num >= 0)) {
Main m = new Main(path, num);
m.deleteFile(dir);
}
} else {
throw new InvalidParameterException("OOPS!");
}
}
}
It runs off a batch file the gives the command java -cp . MainCopy "C:\Black" 5
the 5 controls how many days etc over to then delete, this is perfect.
However, i need it to delete just files on a server 2008. The files needed to be over 30 days so. java -cp . MainCopy "C:\Black" 30. However when this command is ran it deletes all the files in the folder.