Waypoint
Waypoint

Reputation: 17753

Java - set file creation date and time

I have found solution how to set last modified time in Java for specific file (Android: How to get & set directory modification date).

Is there a way to set creation date and time in Java for specific file as well?

Upvotes: 0

Views: 6808

Answers (3)

Surya Kameswara Rao Ravi
Surya Kameswara Rao Ravi

Reputation: 1556

This does not work on MAC for OSX a UNIX variant using HFS file system.

import java.io.*;
import java.util.*;
import java.nio.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;

class changetime{

    public static void main(String args[]){

        Path p = Paths.get("./test.txt");
        System.out.println(p);
        try {
                Calendar c = Calendar.getInstance();
                c.set(2010, Calendar.MARCH, 20);
                Files.setAttribute(p, "basic:creationTime", FileTime.fromMillis(c.getTimeInMillis()), NOFOLLOW_LINKS);
        } catch (IOException e) {
                System.err.println("Cannot change the creation time. " + e);
        }
    }//END Main

}//END Class

Upvotes: 0

Oleksandr Tsurika
Oleksandr Tsurika

Reputation: 980

In java 7 it is possible to set creation time to directory or file using such code:

//date which is used as date of creation
Date creationDate;
//path to directory of file to which to set creation time
Path somePath;
...
FileTime time = FileTime.fromMillis(creationDate.getTime());
Files.setAttribute(somePath, "creationTime", time);

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 691685

Exactly the same way. A Date contains an instant in time, with a millisecond precision. Just change the format used to parse the date. Read the documentation for that.

Upvotes: 3

Related Questions