How do I programmatically change file permissions?

前端 未结 12 1036
深忆病人
深忆病人 2020-11-22 04:55

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 t

相关标签:
12条回答
  • 2020-11-22 05:37
    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:38

    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.

    0 讨论(0)
  • 2020-11-22 05:39

    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.

    0 讨论(0)
  • 2020-11-22 05:43

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

    0 讨论(0)
  • 2020-11-22 05:45

    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.

    0 讨论(0)
  • 2020-11-22 05:45
    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

    0 讨论(0)
提交回复
热议问题