Files.setAttribute() and Files.setLastModifiedTime()
What You'll Learn
You'll learn how to programmatically modify file attributes and timestamps, including how to handle platform-specific limitations.
Modifying File Attributes
While Files.readAttributes() lets you read file metadata, NIO.2 also provides methods to change these attributes after a file is created. This is useful for tasks like preserving timestamps when copying files manually, updating access times, or modifying permissions.
Files.setAttribute()
The Files.setAttribute() method sets a single file attribute:
Path path = Paths.get("example.txt");
// Set a specific attribute (syntax: "view:attribute")
Files.setAttribute(path, "dos:hidden", true);
Files.setAttribute(path, "posix:permissions",
PosixFilePermissions.fromString("rw-r--r--"));
The first parameter is the attribute name in "view:attribute" format. Common views include basic, dos, posix, and unix. Note: Many attributes are platform-specific—setting DOS attributes on Linux or POSIX permissions on Windows will throw UnsupportedOperationException.
Files.setLastModifiedTime()
Since modifying timestamps is so common, there's a dedicated convenience method:
Path path = Paths.get("document.txt");
// Set modified time to a specific instant
FileTime newTime = FileTime.fromMillis(System.currentTimeMillis());
Files.setLastModifiedTime(path, newTime);
// Or preserve time from another file
FileTime originalTime = Files.getLastModifiedTime(originalPath);
Files.setLastModifiedTime(copyPath, originalTime);
This method is more convenient than setAttribute(path, "basic:lastModifiedTime", time) and works consistently across platforms.
Platform Considerations
Always be aware that file attribute support varies:
- Windows supports DOS attributes (
hidden,readonly) - Unix/Linux supports POSIX permissions
- Some filesystems don't preserve nanosecond-precision timestamps
Key Takeaway: Use Files.setAttribute() for general attribute modification and Files.setLastModifiedTime() as a convenient shortcut for timestamps, but always handle UnsupportedOperationException for platform-specific attributes.