开发者

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.开发者_如何学JAVAtxt").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?


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.


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.


The File represents a path to a file or directory which may or may not exist.

When you rename a file, there is no long a file with the original name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜