Change File and Group Owner in Java

Category: Java   Tags: Java, Java File Handling, Java Path, Java NIO File System

JavaSetFileOwner.java

                                package com.tutorial.java.files;

                                import java.io.IOException;
                                import java.nio.file.Files;
                                import java.nio.file.Path;
                                import java.nio.file.Paths;
                                import java.nio.file.attribute.BasicFileAttributes;
                                import java.nio.file.attribute.FileTime;

                                public class JavaSetFileOwner {

                                    public static void main(String[] args)  throws IOException {
                                        Path file = Paths.get("sample.txt");
                                        UserPrincipal owner = file.getFileSystem().getUserPrincipalLookupService().lookupPrincipalByName("manish");
                                        Files.setOwner(file, owner);

                                        GroupPrincipal group
                                                = file.getFileSystem().getUserPrincipalLookupService()
                                                .lookupPrincipalByGroupName("dev");
                                        Files.getFileAttributeView(file, PosixFileAttributeView.class)
                                                .setGroup(group);
                                    }
                                }