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
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 -
OUTPUT of the above code
Explanation of the code
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 -
- An instance of
java.nio.files.Path
needs to be created using the actual path to the file in the file system. - Then using
java.nio.file.Files
class the attributes can be read asboolean
values using the following methods with thePath
instance created in step 1 passed as a parameter to the method -FileSystem.isReadable()
- checks whether file is readableFileSystem.isWritable()
- checks whether file is writableFileSystem.isExecutable()
- checks whether file is executable
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);
}
}
Is file readable: true Is file writable: true Is file executable: true
- The class
CheckFileAttributes
fetches the file attributes or permissions for a file namedfile1.txt
. - It first creates a
Path
instance, namedfilePath
, 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 theString
path value on the Windows file system.) filePath
is then passed as a parameter to three attribute checking methods -Files.isReadable()
,Files.isWritable()
andFiles.isExecutable()
.- The printed output shows that
file1.txt
is readable, writable, and executable, as the value returned by all three methods istrue
.