0

I want to give the chmod 700 permission to a file using java.

Code I used

Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
    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);

Path FilePathObject = Paths.get(fileDir.toString(),"fileRun.sh");
Files.setPosixFilePermissions(FilePathObject, perms);

But it is not setting permission correctly -

drwxrwsr-x   4 user group       94 Aug 12 05:45 scriptconfig

I tried this code as well to set the 700 permission -

    txtFilePath.toFile().setExecutable(false,true);
    txtFilePath.toFile().setReadable(false, true);
    txtFilePath.toFile().setWritable(false,true);

But this is also not working as per the expectation. Do we have any thing through which we can set these permissions.

Java_Alert
  • 1,159
  • 6
  • 24
  • 50

2 Answers2

1

Simply try

txtFilePath.toFile().setExecutable(true);
txtFilePath.toFile().setReadable(true);
txtFilePath.toFile().setWritable(true);

else you can check below

How do i programmatically change file permissions?

Community
  • 1
  • 1
Vivek Gupta
  • 955
  • 4
  • 7
0

This code Will be working, if you want to give 770 permission to a file -

Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
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);

Path FilePathObject = Paths.get(fileDir.toString(),"fileRun.sh");
Files.setPosixFilePermissions(FilePathObject, perms);

Note : You have to create the directory before executing given command then only it will work otherwise directory will be created with default permissions.

First create the directory then you can use

PosixFilePermission API introduced in Java 1.7.

`

Java_Alert
  • 1,159
  • 6
  • 24
  • 50