File Permissions in Java
Java provides a number of method calls to check and change the permission of a file, such as a read-only file can be changed to have permissions to write. File permissions are required to be changed when the user wants to restrict the operations permissible on a file. For example, file permission can be changed from write to read-only because the user no longer wants to edit the file.
Checking the Current File Permissions
A file can be in any combination of the following permissible permissions depicted by methods below in tabular format/
|canExecutable()||Returns true if and only if the abstract pathname exists and the application is allowed to execute the file|
|canRead()||Tests whether the application can read the file denoted by this abstract pathname|
|canWrite()||Returns true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise|
Implementation: A file can be readable and writable but not executable. Here’s a Java program to get the current permissions associated with a file.
Changing File Permissions
A file in Java can have any combination of the following permissions:
Here are methods to change the permissions associated with a file as depicted in a tabular format below as follows:
|setExecutable()||Set the owner’s execute permission for this abstract pathname|
|setReadable()||Set the owner’s read permission for this abstract pathname|
|setWritable()||Set the owner’s write permission for this abstract pathname|
- setReadable() Operation will fail if the user does not have permission to change the access permissions of this abstract path name. If readable is false and the underlying file system does not implement a read permission, then the operation will fail.
- setWritable() Operation will fail if the user does not have permission to change the access permissions of this abstract pathname.
This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.