Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't setLastModified(time) work for this File?

Tags:

java

date

file

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

fLocal.location = Existing file in C:\

fLocal.date = Date to set in 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
like image 813
bbholzbb Avatar asked Feb 15 '13 22:02

bbholzbb


2 Answers

From my comments from earlier, follow these checks:

  1. Does your code have write access to the file?
  2. Is the file in open status?
  3. Are you currently reading (or writing!) the file with any other application at the time you are doing this?

These are all items that might prevent you from changing the time of the file.

Create a simple plain text file with a single line of text, save it and close out of the editor. Then try using that file in your application. Make sure you call exists() on your File Object before you try to change the time of it to ensure you actually have a valid file.

like image 98
JoshDM Avatar answered Oct 03 '22 09:10

JoshDM


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

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

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)));
    }
}
like image 21
Amit Avatar answered Oct 03 '22 09:10

Amit