Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java set file permissions to 777 while creating a file object [duplicate]

Possible Duplicate:
How can I set the umask from within java?

How do you set file permissions to 777(or any other arbitrary permission) while creating a file object in java?

like image 504
Abhishek Avatar asked Jun 03 '11 23:06

Abhishek


People also ask

How do I change permissions on a file in Java?

setWritable() − This method is used to set the write permissions to the file represented by the current (File) object. setReadable() − This method is used to set the read permissions to the file represented by the current (File) object.

What is set permission 777?

777 is a permission in Unix based system with full read/write/execute permission to owner, group and everyone.. in general we give this permission to assets which are not much needed to be hidden from public on a web server, for example images..


1 Answers

Java SE 7 has java.nio.file.attribute.PosixFileAttributes which gives you fine grained control over read, write, and execute permissions for owner, group, and others.

import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Set;

public class Test {
    public static void main(String[] args) throws Exception {
        Path path = Paths.get("/tmp/test-file.txt");
        if (!Files.exists(path)) Files.createFile(path);
        Set<PosixFilePermission> perms = Files.readAttributes(path,PosixFileAttributes.class).permissions();

        System.out.format("Permissions before: %s%n",  PosixFilePermissions.toString(perms));

        perms.add(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(path, perms);

        System.out.format("Permissions after:  %s%n",  PosixFilePermissions.toString(perms));
    }
}

Which can then be used like:

$ rm -f /tmp/test-file.txt && javac Test.java && java Test
Permissions before: rw-r--r--
Permissions after:  rwxrwxrwx
like image 131
2 revs, 2 users 95% Avatar answered Sep 18 '22 14:09

2 revs, 2 users 95%