Close

Java IO & NIO - Files.isReadable() Examples

Java IO & NIO Java Java API 


Class:

java.nio.file.Files

java.lang.Objectjava.lang.Objectjava.nio.file.Filesjava.nio.file.FilesLogicBig

Method:

public static boolean isReadable(Path path)

Tests whether a file is readable.

Parameters:
path - the path to the file to check
Returns:
true if the file exists and is readable; false if the file does not exist, read access would be denied because the Java virtual machine has insufficient privileges, or access cannot be determined


Examples


package com.logicbig.example.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class IsReadableExample {

public static void main(String... args) throws IOException {
Path tempFile = Files.createTempFile("test-file", ".txt");
boolean readable = Files.isReadable(tempFile);
System.out.println("file: " + tempFile);
System.out.println("readable: " + readable);
}
}

Output

file: C:\Users\Joe\AppData\Local\Temp\test-file13230566048405783793.txt
readable: true




package com.logicbig.example.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.AclEntry;
import java.nio.file.attribute.AclEntryPermission;
import java.nio.file.attribute.AclEntryType;
import java.nio.file.attribute.AclFileAttributeView;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


public class IsReadableExample2 {

public static void main(String... args) throws IOException {
Path tempFile = Files.createTempFile("test-file", ".txt");
System.out.println("Denying read permission to owner: " + tempFile);
//on windows
AclFileAttributeView view = Files.getFileAttributeView(tempFile, AclFileAttributeView.class);
Set<AclEntryPermission> newPermissions =
new HashSet<>(Arrays.asList(AclEntryPermission.values()));
newPermissions.remove(AclEntryPermission.READ_DATA);
AclEntry entry = AclEntry.newBuilder()
.setType(AclEntryType.ALLOW)
.setPrincipal(Files.getOwner(tempFile))
.setPermissions(newPermissions)
.build();
view.setAcl(Arrays.asList(entry));

Path filePath = Paths.get(tempFile.toString());
boolean readable = Files.isReadable(filePath);
System.out.println("file: " + filePath);
System.out.println("readable: " + readable);
}
}

Output

Denying read permission to owner: C:\Users\Joe\AppData\Local\Temp\test-file17267436563626020769.txt
file: C:\Users\Joe\AppData\Local\Temp\test-file17267436563626020769.txt
readable: false




See Also