Attempting to set last modified file time in Java after renaming it

Here is the code that I started 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 result that 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);

Everything seemed to be fine with this output:

renamed: true
time changed: true

Why does the second approach work, but the first does not?

+5
source share
3 answers

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

- , Java . old = new File("oldname"), rename, old, . .

, .

+4

oldFile.renameTo(new File("new_name.txt")); , oldFile. oldFile - old_name.txt .

, setLastModified , old_name.txt .

+2

File represents the path to a file or directory that may or may not exist.

When renaming a file, a long file with the original name is missing.

+1
source

All Articles