Get the file creation time Tag(s): IO


Java.io.File returns the last modified time. To get the creation time, you need to use java.nio.Paths class.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.SimpleDateFormat;

public class FileCreationTime {

  public static FileTime getCreationTime(File file) throws IOException {
    Path p = Paths.get(file.getAbsolutePath());
    BasicFileAttributes view
        = Files.getFileAttributeView(p, BasicFileAttributeView.class)
                    .readAttributes();
    FileTime fileTime=view.creationTime();
    //  also available view.lastAccessTine and view.lastModifiedTime
    return fileTime;
  }

  public static void main(String[] args) throws IOException {
    File file = new File("c:/temp/images.jpg");
    System.out.println(file + " creation time :"
        + new SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
                   .format(FileCreationTime.getCreationTime(file).toMillis()));
  }
}

blog comments powered by Disqus