BasicFileAttributeView Sets File Times

Rewrite lastModifiedTime and lastAccessTime explicitly through the attribute view so archival copies keep the original timestamps.

JavaData Integrity

Code

snippet
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;

public class TimestampPreserver {

    public static void main(String[] args) throws IOException {
        Path archive = Files.createTempFile("archive-", ".txt");
        Files.writeString(archive, "quarterly report");

        // 写入会刷新 mtime;归档场景要把原始时间补回去
        BasicFileAttributeView view =
                Files.getFileAttributeView(archive, BasicFileAttributeView.class);
        BasicFileAttributes written = view.readAttributes();
        System.out.println("after write : " + written.lastModifiedTime());

        FileTime shipped = FileTime.fromMillis(1_700_000_000_000L); // 2023-11-14T22:13:20Z
        view.setTimes(shipped, null, null); // null 表示对应时间保持不变

        BasicFileAttributes after = view.readAttributes();
        System.out.println("after set   : " + after.lastModifiedTime());
        System.out.println("access kept : "
                + after.lastAccessTime().equals(written.lastAccessTime()));

        Files.deleteIfExists(archive);
    }
}

What the code shows

The snippet creates a temp file, writes a line, then reaches for BasicFileAttributeView via Files.getFileAttributeView. readAttributes() snapshots the write-time mtime, and view.setTimes(shipped, null, null) rewrites lastModifiedTime to FileTime.fromMillis(1_700_000_000_000L) while passing null to keep lastAccessTime and createTime untouched.

Why two readAttributes calls

The first snapshot shows the OS-assigned after-write timestamp; the second confirms the override and that the access time survived unchanged — printed as access kept : true.

Where this applies

Archival flows that copy files lose original timestamps unless they rewrite them; the attribute view is the standard NIO surface for that fix, and Files.deleteIfExists cleans up the demo artifact.

Interactive Tools for This Topic

FAQ

What do the null arguments in setTimes mean?
Each null leaves the corresponding time untouched; the demo only rewrites lastModifiedTime and passes null for lastAccessTime and createTime.
Why use the attribute view instead of Files.setLastModifiedTime?
The view reads all three times back with types and can set them together; it is also the same surface used for other attribute work on the file.