first of all renameTo() works fine, the problem is after it has been renamed, the path of File f is still the old one instead of the new one, in other words File f is unusable, and has to be changed. but how should I do it?
ArrayList<File> list = new ArrayList();
public void myfunction() {
// some code to fill list
for (File f:list){
changeName(f);
System.out.println(f.getName()); // this print the old name
}
}
public void changeName(File f){
File newFile = new File(new SimpleDateFormat("yyyyMMdd_HHmmss").format(f.lastModified())+".txt");
f.renameTo(newFile);
f = newFile; //this line here doesn't work
}
}
It is because in JAVA variables are passed by value
. If you want to see new content then return newFile
, instead of f = newFile;
statement.