How to get file attributes or permissions using Java NIO with examples

This tutorial shows how to get the file attributes for a given file in Java with examples. It uses the Path and Files classes from the Java NIO API to fetch the attribute information of a file from the underlying file system.

The file attributes which can be read for a file are whether it is readable, writable and/or executable. Using Java NIO API the file attributes can be accessed in the following 2 steps –

  1. An instance of java.nio.files.Path needs to be created using the actual path to the file in the file system.
  2. Then using java.nio.file.Files class the attributes can be read as boolean values using the following methods with the Path instance created in step 1 passed as a parameter to the method –
    • FileSystem.isReadable() – checks whether file is readable
    • FileSystem.isWritable() – checks whether file is writable
    • FileSystem.isExecutable() – checks whether file is executable

Let us now see a Java code example showing how to retrieve the attributes of a given file, which is followed by an explanation of the code.

Java NIO-based code example to get permissions for a file
package com.javabrahman.corejava;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

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

    Path filePath = Paths.get("C:\\JavaBrahman\\LEVEL1\\file1.txt");

    //Is file readable
    boolean isReadable = Files.isReadable(filePath);
    System.out.println("Is file readable: " + isReadable);

    //Is file writable
    boolean isWritable = Files.isWritable(filePath);
    System.out.println("Is file writable: " + isWritable);

    //Is file executable
    boolean isExecutable = Files.isExecutable(filePath);
    System.out.println("Is file executable: " + isExecutable);
  }
}
 OUTPUT of the above code
Is file readable: true
Is file writable: true
Is file executable: true
Explanation of the code

  • The class CheckFileAttributes fetches the file attributes or permissions for a file named file1.txt.
  • It first creates a Path instance, named filePath, using the full path of the file("C:\\JavaBrahman\\LEVEL1\\file1.txt") in the file system.(The double backward slashes(‘\\’) are to escape the single backward slash(‘\’) in the String path value on the Windows file system.)
  • filePath is then passed as a parameter to three attribute checking methods –
    Files.isReadable(), Files.isWritable() and Files.isExecutable().
  • The printed output shows that file1.txt is readable, writable, and executable, as the value returned by all three methods is true.

 

Digiprove sealCopyright © 2014-2018 JavaBrahman.com, all rights reserved.