How do I programmatically change file permissions?

JavaFilesystems

Java Problem Overview


In Java, I'm dynamically creating a set of files and I'd like to change the file permissions on these files on a linux/unix file system. I'd like to be able to execute the Java equivalent of chmod. Is that possible Java 5? If so, how?

I know in Java 6 the File object has setReadable()/setWritable() methods. I also know I could make a system call to do this, but I'd like to avoid that if possible.

Java Solutions


Solution 1 - Java

Full control over file attributes is available in Java 7, as part of the "new" New IO facility (NIO.2). For example, POSIX permissions can be set on an existing file with setPosixFilePermissions(), or atomically at file creation with methods like createFile() or newByteChannel().

You can create a set of permissions using EnumSet.of(), but the helper method PosixFilePermissions.fromString() will uses a conventional format that will be more readable to many developers. For APIs that accept a FileAttribute, you can wrap the set of permissions with with PosixFilePermissions.asFileAttribute().

Set<PosixFilePermission> ownerWritable = PosixFilePermissions.fromString("rw-r--r--");
FileAttribute<?> permissions = PosixFilePermissions.asFileAttribute(ownerWritable);
Files.createFile(path, permissions);

In earlier versions of Java, using native code of your own, or exec-ing command-line utilities are common approaches.

Solution 2 - Java

In addition to erickson's suggestions, there's also jna, which allows you to call native libraries without using jni. It's shockingly easy to use, and I've used it on a couple of projects with great success.

The only caveat is that it's slower than jni, so if you're doing this to a very large number of files that might be an issue for you.

(Editing to add example)

Here's a complete jna chmod example:

import com.sun.jna.Library;
import com.sun.jna.Native;

public class Main {
    private static CLibrary libc = (CLibrary) Native.loadLibrary("c", CLibrary.class);

    public static void main(String[] args) {
        libc.chmod("/path/to/file", 0755);
    }
}

interface CLibrary extends Library {
    public int chmod(String path, int mode);
}

Solution 3 - Java

Prior to Java 6, there is no support of file permission update at Java level. You have to implement your own native method or call Runtime.exec() to execute OS level command such as chmod.

Starting from Java 6, you can useFile.setReadable()/File.setWritable()/File.setExecutable() to set file permissions. But it doesn't simulate the POSIX file system which allows to set permission for different users. File.setXXX() only allows to set permission for owner and everyone else.

Starting from Java 7, POSIX file permission is introduced. You can set file permissions like what you have done on *nix systems. The syntax is :

File file = new File("file4.txt");
file.createNewFile();
 
Set<PosixFilePermission> perms = new HashSet<>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
 
Files.setPosixFilePermissions(file.toPath(), perms);

This method can only be used on POSIX file system, this means you cannot call it on Windows system.

For details on file permission management, recommend you to read this post.

Solution 4 - Java

For Windows 7 with NIO 2:

public static void main(String[] args) throws IOException {
	Path file = Paths.get("c:/touch.txt");
	AclFileAttributeView aclAttr = Files.getFileAttributeView(file, AclFileAttributeView.class);
	System.out.println(aclAttr.getOwner());
	for (AclEntry aclEntry : aclAttr.getAcl()) {
		System.out.println(aclEntry);
	}
	System.out.println();
	
	UserPrincipalLookupService upls = file.getFileSystem().getUserPrincipalLookupService();
	UserPrincipal user = upls.lookupPrincipalByName(System.getProperty("user.name"));
	AclEntry.Builder builder = AclEntry.newBuilder();       
	builder.setPermissions( EnumSet.of(AclEntryPermission.READ_DATA, AclEntryPermission.EXECUTE, 
			AclEntryPermission.READ_ACL, AclEntryPermission.READ_ATTRIBUTES, AclEntryPermission.READ_NAMED_ATTRS,
			AclEntryPermission.WRITE_ACL, AclEntryPermission.DELETE
	));
	builder.setPrincipal(user);
	builder.setType(AclEntryType.ALLOW);
	aclAttr.setAcl(Collections.singletonList(builder.build()));
}

Solution 5 - Java

Just to update this answer unless anyone comes across this later, since JDK 6 you can use

File file = new File('/directory/to/file');
file.setWritable(boolean);
file.setReadable(boolean);
file.setExecutable(boolean);

you can find the documentation on Oracle File(Java Platform SE 7). Bear in mind that these commands only work if the current working user has ownership or write access to that file. I am aware that OP wanted chmod type access for more intricate user configuration. these will set the option across the board for all users.

Solution 6 - Java

If you want to set 777 permission to your created file than you can use the following method:

public void setPermission(File file) throws IOException{
    Set<PosixFilePermission> perms = new HashSet<>();
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_EXECUTE);
	
    perms.add(PosixFilePermission.OTHERS_READ);
    perms.add(PosixFilePermission.OTHERS_WRITE);
    perms.add(PosixFilePermission.OTHERS_EXECUTE);
	
    perms.add(PosixFilePermission.GROUP_READ);
    perms.add(PosixFilePermission.GROUP_WRITE);
    perms.add(PosixFilePermission.GROUP_EXECUTE);

    Files.setPosixFilePermissions(file.toPath(), perms);
}

Solution 7 - Java

You can use the methods of the File class: http://docs.oracle.com/javase/7/docs/api/java/io/File.html

Solution 8 - Java

Apache ant chmod (not very elegant, adding it for completeness) credit shared with @msorsky

	Chmod chmod = new Chmod();
	chmod.setProject(new Project());
	FileSet mySet = new FileSet();
	mySet.setDir(new File("/my/path"));
	mySet.setIncludes("**");
	chmod.addFileset(mySet);
	chmod.setPerm("+w");
	chmod.setType(new FileDirBoth());
	chmod.execute();

Solution 9 - Java

for Oralce Java 6:

private static int chmod(String filename, int mode) {
    try {
        Class<?> fspClass = Class.forName("java.util.prefs.FileSystemPreferences");
        Method chmodMethod = fspClass.getDeclaredMethod("chmod", String.class, Integer.TYPE);
        chmodMethod.setAccessible(true);
        return (Integer)chmodMethod.invoke(null, filename, mode);
    } catch (Throwable ex) {
        return -1;
    }
}

works under solaris/linux.

Solution 10 - Java

There is an example class on Oracle Docs which works very much similar to the UNIX chmod. It works with java se 7+ though.

Solution 11 - Java

simple java code  for change file permission in java  

   String path="D:\\file\\read.txt";
        File file=new File(path);
        if (file.exists()) {
            System.out.println("read="+file.canRead());
            System.out.println("write="+file.canWrite());
            System.out.println("Execute="+file.canExecute());
            file.setReadOnly();
        }     

Reference : how to change file permission in java

Solution 12 - Java

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;

public class FileAndDirectory1 {
    public static void main(String[] args) {
        
        File file = new File("fileTest1.txt");
        System.out.println(file.getAbsoluteFile());
        try {
            //file.createNewFile();
            if(!file.exists())
            {
                //PosixFilePermission is an enum class, PosixFilePermissions is a final class
                
                //create file permissions from string
                Set<PosixFilePermission> filePermissions = PosixFilePermissions.fromString("---------"/* "rwxrwxrwx" */);
                FileAttribute<?> permissions = PosixFilePermissions.asFileAttribute(filePermissions);
                Files.createFile(file.toPath(), permissions);
                // printing the permissions associated with the file
                System.out.println("Executable: " + file.canExecute());
                System.out.println("Readable: " + file.canRead());
                System.out.println("Writable: "+ file.canWrite());

                file.setExecutable(true);
                file.setReadable(true);
                file.setWritable(true);
            }
            else
            {
                //modify permissions
                
                //get the permission using file attributes
                Set<PosixFilePermission> perms = Files.readAttributes(file.toPath(), PosixFileAttributes.class).permissions();
                perms.remove(PosixFilePermission.OWNER_WRITE);

                perms.add(PosixFilePermission.OWNER_READ);
                perms.add(PosixFilePermission.OWNER_EXECUTE);
                perms.add(PosixFilePermission.GROUP_WRITE);
                perms.add(PosixFilePermission.GROUP_READ);
                perms.add(PosixFilePermission.GROUP_EXECUTE);
                perms.add(PosixFilePermission.OTHERS_WRITE);
                perms.add(PosixFilePermission.OTHERS_READ);
                perms.add(PosixFilePermission.OTHERS_EXECUTE);
                Files.setPosixFilePermissions(file.toPath(), perms);

                System.out.println("Executable: " + file.canExecute());
                System.out.println("Readable: " + file.canRead());
                System.out.println("Writable: "+ file.canWrite());

                file.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Path path = Paths.get(String.valueOf(file));
        System.out.println(path);
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoy RicoView Question on Stackoverflow
Solution 1 - JavaericksonView Answer on Stackoverflow
Solution 2 - JavaMarty LambView Answer on Stackoverflow
Solution 3 - JavaPixelsTechView Answer on Stackoverflow
Solution 4 - JavabobView Answer on Stackoverflow
Solution 5 - JavaTravisFView Answer on Stackoverflow
Solution 6 - JavaApoorv ChourasiyaView Answer on Stackoverflow
Solution 7 - JavaErel Segal-HaleviView Answer on Stackoverflow
Solution 8 - JavaihadannyView Answer on Stackoverflow
Solution 9 - JavaVladView Answer on Stackoverflow
Solution 10 - Javajan.supolView Answer on Stackoverflow
Solution 11 - JavaAnuj DhimanView Answer on Stackoverflow
Solution 12 - JavaUddhav P. GautamView Answer on Stackoverflow