Java IO & NIO - Files.setPosixFilePermissions() Examples

Code Snippets Java IO & NIO Java 


Class:

java.nio.file.Files

java.lang.Objectjava.lang.Objectjava.nio.file.Filesjava.nio.file.FilesLogicBig

Method:

public static Path setPosixFilePermissions(Path path,
                                           Set<PosixFilePermission> perms)
                                    throws IOException

Sets a file's POSIX permissions.

Parameters:
path - The path to the file
perms - The new set of permissions
Returns:
The path


Examples


package com.logicbig.example.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class SetPosixFilePermissionsExample {

public static void main(String... args) throws IOException {
Path path = Files.createTempFile("test-file", ".txt");
System.out.println(path);

System.out.println("- posix permission before --");
printPosixPermissions(path);

//setting posix permissions
Set<PosixFilePermission> permissions = new HashSet<>();
permissions.add(PosixFilePermission.OTHERS_WRITE);
Files.setPosixFilePermissions(path, permissions);

System.out.println("- posix permission after --");
printPosixPermissions(path);
}

private static void printPosixPermissions(Path path) throws IOException {
Map<String, Object> attributes = Files.readAttributes(path, "posix:*");
attributes.entrySet()
.forEach(e -> System.out.printf("%s = %s%n", e.getKey(), e.getValue()));
}
}

Output in Linux Mint 18.1:

This example will fail in Windows.

 /tmp/test-file331724472763753480.txt
-- posix permission before --
owner = joe
lastAccessTime = 2017-12-17T20:09:30.733998Z
lastModifiedTime = 2017-12-17T20:09:30.733998Z
size = 0
creationTime = 2017-12-17T20:09:30.733998Z
isSymbolicLink = false
permissions = [OWNER_WRITE, OWNER_READ]
isRegularFile = true
fileKey = (dev=801,ino=4591941)
isOther = false
isDirectory = false
group = joe
-- posix permission after --
owner = joe
lastAccessTime = 2017-12-17T20:09:30.733998Z
lastModifiedTime = 2017-12-17T20:09:30.733998Z
size = 0
creationTime = 2017-12-17T20:09:30.733998Z
isSymbolicLink = false
permissions = [OTHERS_WRITE]
isRegularFile = true
fileKey = (dev=801,ino=4591941)
isOther = false
isDirectory = false
group = joe




See Also