Search code examples
javalast-modifiedfile-rename

Trying to set the last modified time of a file in Java after renaming it


Here's the code I started off with:

long modifiedTime = [some time here];
File oldFile = new File("old_name.txt");
boolean renamed = oldFile.renameTo(new File("new_name.txt");
boolean timeChanged = oldFile.setLastModified(modifiedTime);

System.out.println("renamed: " + renamed);
System.out.println("time changed: " + timeChanged);

And the output I saw was:

renamed: true
time changed: false

But when I tried:

long modifiedTime = [some time here];
boolean renamed = new File("old_name.txt").renameTo(new File("new_name.txt"));
boolean timeChanged = new File("new_name.txt").setLastModified(modifiedTime);

System.out.println("renamed: " + renamed);
System.out.println("time changed: " + timeChanged);

It seemed to work fine, with this output:

renamed: true
time changed: true

Why is it that the second approach works, and the first one doesn't?


Solution

  • In first case you are trying to change the last modified attribute of file that no longer exists! Because you have just renamed it. In second case you are changing the attribute of existing valid file.

    This happens because java class File is a thin wrapper over native commands. If you created instance old = new File("oldname"), then called rename and then invoked some method on old instance it actually performs system call and sends both the file name and the command. But the file name is irrelevant at this point.

    I hope now it is clear.