0

I have a piece of Java code that will create a new file and fill it with existing data elsewhere. When right clicking on the file and looking at its properties. There will be this property "Created" and "Modified" which are set to the date when the file was created by the code.

I would like to retain the Created/Modified date that the old file had. Is it possible?

    ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
    if (reader == null)
    {
        // no data for this node
        return false;
    }

    File output = new File(outputFileName);
    reader.getContent(output);
Plv90
  • 7
  • 2

2 Answers2

0

File metadata can be fetched as File attributes. Sample example is as below.

File attributes is part of java.nio.file.attribute package.

File file = new File(outputFileName);
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);

System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());

System.out.println("isDirectory: " + attr.isDirectory());
System.out.println("isOther: " + attr.isOther());
System.out.println("isRegularFile: " + attr.isRegularFile());
System.out.println("isSymbolicLink: " + attr.isSymbolicLink());
System.out.println("size: " + attr.size());

This should give you required details.

Mukund Desai
  • 100
  • 2
0

See https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/BasicFileAttributeView.html and/or https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/attribute/BasicFileAttributeView.html

"The setAttribute method may be used to update the file's last modified time, last access time or create time attributes as if by invoking the setTimes method."

Erwin Smout
  • 18,113
  • 4
  • 33
  • 52
  • Using setAttribute to set creationTime and lastModifiedTime worked on Windows. However, on Linux it seems creationTime won't be set. As far as I know, Linux isn't supporting the creationTime. I moved the file over to a Windows machine and from the looks of it only the lastModifiedTime is set. I found old comments where people reported that it doesn't work so well on macOS and certain Linux. – Plv90 Sep 14 '19 at 16:35