Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 715
K Mehta Avatar asked Jul 24 '11 08:07

K Mehta


2 Answers

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.

like image 187
AlexR Avatar answered Sep 30 '22 13:09

AlexR


oldFile.renameTo(new File("new_name.txt")); does not change where oldFile points. oldFile's path is still old_name.txt after that call.

So the setLastModified call fails because old_name.txt no longer exists at that point.

like image 23
Mat Avatar answered Sep 30 '22 13:09

Mat