Why does the setLastModified (time) function not work for this file?

Why is the file date in the following code not changed?

fLocal.location = Existing file in C: \

fLocal.date = Date to set to Long

 boolean x = new File(fLocal.location).setLastModified(Long.parseLong(fLocal.date)); System.out.println("Changed: " + x); System.out.println(new Date(new File(fLocal.location).lastModified())); System.out.println(new Date(Long.parseLong(fLocal.date))); 

Output:

 Changed: false Fri Feb 15 23:02:51 CET 2013 Fri Feb 15 22:49:34 CET 2013 
+6
source share
2 answers

From my comments earlier, do the following checks:

  • Does your code have write access to the file?
  • Is the file an open status?
  • Are you currently reading (or writing!) A file with any other application while you are doing this?

These are all elements that may prevent you from changing the file time.

Create a simple text file with one line of text, save it and close it from the editor. Then try using this file in your application. Make sure you call exists() on the File Object before trying to change the time of it to make sure you really have a valid file.

+2
source

I tested your code on my local computer and it works ... I changed the modified date of a very old file on my system ...

-See if the file is being used somewhere else ... -check if you have file permissions

 import java.io.File; import java.io.IOException; import java.util.Date; class Test { private class flocalClass { public String date; public String location="c:/Test/cascade.xyz"; } public static void main (String[]args) throws IOException { flocalClass fLocal = new Test().new flocalClass(); fLocal.date = Long.toString(new Date().getTime()); boolean x = new File(fLocal.location).setLastModified(Long.parseLong(fLocal.date)); System.out.println("Changed: " + x); System.out.println(new Date(new File(fLocal.location).lastModified())); System.out.println(new Date(Long.parseLong(fLocal.date))); } } 
+2
source

All Articles