Create directory with permissions in java

Let’s learn create directory with permissions in java.

Create directory with permissions in java

To java create directory with permissions use PosixFilePermissions.

NOTE: PosixFilePermissions class cannot be used for Windows systems.

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.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
public class CreateDirectoryPermissions 
{
   public static void main(String[] args) throws IOException 
   {
      String strFile = "/javaexamples/sachin/dir/newDir";
      Path path = Paths.get(strFile);
      if(!Files.exists(path))
      {
         Set<PosixFilePermission> permission = PosixFilePermissions.fromString("rwxr--r--");
         FileAttribute<Set<PosixFilePermission>> file = PosixFilePermissions.asFileAttribute(permission);
         Files.createDirectory(path, file);
         System.out.println("Directory created");
      }
      else 
      {
         System.out.println("Oops!!Directory already exists");
      }
   }
}



Also read – variables in java