Restrict File Access With POSIX Permissions
Tighten a secret file to owner read/write with PosixFilePermissions, probing filesystem support first so non-POSIX systems degrade cleanly.
Code
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
public class SecretFilePermissions {
public static void main(String[] args) throws IOException {
Path secret = Files.createTempFile("token-", ".key");
Files.writeString(secret, "s3cr3t-token");
// POSIX 权限只在 POSIX 文件系统可用:先探测再收紧
if (secret.getFileSystem().supportsFileAttributeView("posix")) {
// restrict the secret file to owner read/write only (rw-------)
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-------");
Files.setPosixFilePermissions(secret, perms);
System.out.println("permissions: "
+ PosixFilePermissions.toString(Files.getPosixFilePermissions(secret)));
} else {
System.out.println("posix view not supported on this filesystem");
}
Files.deleteIfExists(secret);
}
}Inside the snippet
Restrict File Access With POSIX Permissions reduces to the class SecretFilePermissions.
Watch out for
- There is no dependency tree here — the platform is the whole dependency.
Putting it to use
The file announces its steps in the output: permissions:, posix view not supported on this filesystem.
Core lines
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-------");
Path secret = Files.createTempFile("token-", ".key");
Files.setPosixFilePermissions(secret, perms);
Interactive Tools for This Topic
Unix Permissions CalculatorConvert between octal and symbolic Unix file permissions and explain read/write/execute plus setuid, setgid, and sticky bits.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- What does Restrict File Access With POSIX Permissions print when run?
- Invoke the file as-is — the `permissions:`, `posix view not supported on this filesystem` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.