SagittariusA
SagittariusA

Reputation: 5427

Java: Set file permissions to several users

For a little application that I'm writing there's a file.xml which is a database.

When the file.xml is created with:

File xmlDB = new File(newYear + ".xml");
PrintWriter writer = new PrintWriter(newYear+".xml", "UTF-8");
String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><economato> </economato>";
writer.println(header);

then I can set permissions with

xmlDB.setwReadable()
XML.setWritable()

but I've understood that with these primitives I can set the permission either for the owner of for everyone. Instead how can I set these permissions for 2 or 3 people (of given their username they use to log in into the server?)??

I'd need to know this for Linux but overall for Windows. Am I supposed to use

Runtime.getRuntime().exec("Windows prompt command");

to do that?

Thanks

Upvotes: 0

Views: 832

Answers (1)

paul
paul

Reputation: 13471

You can add permisions to groups and then add those users that you want to that groups

   //using PosixFilePermission to set file permissions 777
    Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
    //add owners permission
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_EXECUTE);
    //add group permissions
    perms.add(PosixFilePermission.GROUP_READ);
    perms.add(PosixFilePermission.GROUP_WRITE);
    perms.add(PosixFilePermission.GROUP_EXECUTE);
    //add others permissions
    perms.add(PosixFilePermission.OTHERS_READ);
    perms.add(PosixFilePermission.OTHERS_WRITE);
    perms.add(PosixFilePermission.OTHERS_EXECUTE);

    Files.setPosixFilePermissions(Paths.get("/Users/pankaj/run.sh"), perms);

Upvotes: 1

Related Questions