Extract the POSIX permissions of a file and create another file with the same attributes - Java File Path IO

Java examples for File Path IO:Unix File

Description

Extract the POSIX permissions of a file and create another file with the same attributes

Demo Code

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.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;

public class Main {
  public static void main(String[] args) {

    PosixFileAttributes attr = null;
    Path path = Paths.get("/home/folder1/folder2/folder3/test.txt");
    try {/* w w w .ja  va2 s  .c  o  m*/
      attr = Files.getFileAttributeView(path, PosixFileAttributeView.class)
          .readAttributes();
    } catch (IOException e) {
      System.err.println(e);
    }
    System.out.println("File owner: " + attr.owner().getName());
    System.out.println("File group: " + attr.group().getName());
    System.out.println("File permissions: " + attr.permissions().toString());
    
    Path new_path = Paths.get("/home/folder1/folder2/folder3/new_test.txt");  
    FileAttribute<Set<PosixFilePermission>> posixattrs =    
                           PosixFilePermissions.asFileAttribute(attr.permissions());  
    try {  
        Files.createFile(new_path, posixattrs);  
    } catch (IOException e) {  
        System.err.println(e);  
    }      
  }
}

Related Tutorials