In Java, Files.setAttribute(path, "view:name", value) changes one attribute of a file. It uses the same names as getAttribute, and the value must have the matching type, for example a FileTime for times or a Boolean for DOS flags.
Only writable attributes can be set: the basic view allows the three timestamps, the dos view (Windows) allows readonly, hidden, system, and archive, and the posix view allows permissions, owner, and group.
A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.setAttribute(...), after import java.nio.file.Files;. You never create a Files object.
Syntax
Path, attribute name, and a correctly typed value:
Run with java SetAttributeDosReadOnly. First part: Windows. Last part: Linux or macOS, where the read-only state comes from POSIX permissions.
dos:readonly = true
isWritable: false
Cleared, isWritable: true
--- Linux or macOS ---
Not Windows: use POSIX permissions instead
How It Works
Pick the platform. Linux can also offer a dos view (stored in extended attributes), so the test also requires that posix is absent, which means Windows.
The flag matters. On Windows, isWritable checks the DOS read-only flag, so it turns false.
Clear before delete. Windows refuses to delete a read-only file with AccessDeniedException, so the flag is set back to false first.
Frequently Asked Questions
Files.setAttribute(path, "dos:readonly", true). On Linux and macOS, remove the write bits with Files.setPosixFilePermissions instead.
Timestamps in basic; readonly, hidden, system, and archive in dos; permissions, owner, and group in posix; owner in owner.
The value has the wrong type, for example a long where a FileTime is needed.
No. basic:size is read-only; truncate through a channel from Files.newByteChannel.
Yes, by default. Pass LinkOption.NOFOLLOW_LINKS to change the link itself where the system allows it.