Android: How to get & set directory modification d

2019-09-03 11:40发布

问题:

I'm looking for a way to get a directories modification date. I've tried:

File dir = new File(myDir);
long mod = dir.lastModified();

But it's returning 0.

I'm also looking for a way to set the last modification date of a directory but haven't found anything.

Is there a documented way to do these?

回答1:

Edit: Your code looks right, Just check the existence of directory..

public long lastModified ()

Returns the time when this file was last modified, measured in milliseconds since January 1st, 1970, midnight. Returns 0 if the file does not exist.

So just check whether your file is exist or not..

CODE:

For get Last modified date from file,

File file = new File("Your file path");
Date lastModDate = new Date(file.lastModified());
Log.i("File last modified : "+ lastModDate.toString());

To set Last Modified date to a file..

try{

    File file = new File("/mnt/sdcard/temp.txt");

    //print the original last modified date
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    Log.i("Original Last Modified Date : " , ""+sdf.format(file.lastModified()));

    //set this date 
    String newLastModified = "01/06/2012";

    //need convert the above date to milliseconds in long value 
    Date newDate = sdf.parse(newLastModified);
    file.setLastModified(newDate.getTime());

    //print the latest last modified date
    Log.i("Lastest Last Modified Date : ", ""+sdf.format(file.lastModified()));

    }catch(ParseException e){
        e.printStackTrace();
    }


回答2:

The long variable returned by object dir needs to be converted like below, using your example.

File dir = new File(myDir);
long mod = dir.lastModified();
Date lastModify = new Date(mod);

For date setting, try function setLastModified( long Time ).

For reference, a Java link @ Java 1.7



回答3:

I hope your myDir contains the path of directory

Following snippet works for me

        File file1 = new File(getFilesDir().getAbsolutePath());
        Log.i("text", "" + file1.lastModified());