9

I need not last modification time and not last file accessed time, but file creation time. I have not found information about this. Maybe some libs?

Path p = Paths.get(f.getAbsoluteFile().toURI());
BasicFileAttributes view = null;
try {
    view = Files.getFileAttributeView(p,
                            BasicFileAttributeView.class).readAttributes();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
FileTime creationTime = view.creationTime();

In this code creation time is not valid and return today date.

Operation System: Windows 7 Java: SE-1.7

Nunser
  • 4,494
  • 8
  • 22
  • 35
Igor Kostenko
  • 2,494
  • 5
  • 27
  • 55

3 Answers3

10

As yshavit said, not all operating systems record the date created. However, you should be able to use java.nio.file to determine this information on operating systems that do have this functionality - see the documentation for files.getAttribute - note that BasicFileAttributeView has a field for creationTime.

You can use FileSystems.getDefault(); to determine what FileAttributeViews are supported on the current operating system.

Files.getAttribute(path, "basic:createdAt"); will return a FileTime object with the date the file was created on a system that supports BasicFileAttributeView. You'll have to convert it to a java.util.Date object, but I'll let you figure that out on your own.

Further Reading

  • NIO API for getAttribute()
  • NIO API for BasicFileAttributeView
  • A tutorial for using readAttributes()
  • A comprehensive tutorial on using FileAttributes
  • Another StackOverflow thread on the same topic
Community
  • 1
  • 1
Eliza Weisman
  • 823
  • 9
  • 17
6

How to get the creation date of a file in Java, using BasicFileAttributes class, this is an example:

   Path path = Paths.get("C:\\Users\\jorgesys\\workspaceJava\\myfile.txt");
    BasicFileAttributes attr;
    try {
    attr = Files.readAttributes(path, BasicFileAttributes.class);

    System.out.println("Creation date: " + attr.creationTime());

    } catch (IOException e) {
    System.out.println("oops error! " + e.getMessage());
    }
Jorgesys
  • 114,263
  • 22
  • 306
  • 247
3

You won't be able to do this across all systems, since not all systems even record that information. Linux doesn't, for instance; see this SO thread.

Many programs "modify" a file by copying it, making a change on the copy, and then moving the copy to the original file's location. So for those, there's not a meaningful distinction between creation and last-modification.

Community
  • 1
  • 1
yshavit
  • 39,951
  • 7
  • 75
  • 114