close
The Wayback Machine - https://web.archive.org/web/20241005072301/https://www.geeksforgeeks.org/file-permissions-java/
Open In App

File Permissions in Java

Last Updated : 22 Apr, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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/

Method Action Performed
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.

Example:

Java




// Java Program to Check the Current File Permissions
 
// Importing required classes
import java.io.*;
 
// Main class
public class Test {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating a file by
        // creating object of File class
        File file
            = new File("C:\\Users\\Mayank\\Desktop\\1.txt");
 
        // Checking if the file exists
        // using exists() method of File class
        boolean exists = file.exists();
        if (exists == true) {
 
            // Printing the permissions associated
            // with the file
            System.out.println("Executable: "
                               + file.canExecute());
            System.out.println("Readable: "
                               + file.canRead());
            System.out.println("Writable: "
                               + file.canWrite());
        }
 
        // If we enter else it means
        // file does not exists
        else {
            System.out.println("File not found.");
        }
    }
}


Output:

BERJAYA

Changing File Permissions

A file in Java can have any combination of the following permissions: 

  • Executable
  • Readable
  • Writable

Here are methods to change the permissions associated with a file as depicted in a tabular format below as follows:

Method Action Performed
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

Note:

  • 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.

 Example:

Java




// Java Program to Change File Permissions
 
// Importing required classes
import java.io.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a new file by
        // creating object of File class where
        // local directory is passed as in argument
        File file
            = new File("C:\\Users\\Mayank\\Desktop\\1.txt");
 
        // Checking if file exists
        boolean exists = file.exists();
        if (exists == true) {
 
            // Changing the file permissions
            file.setExecutable(true);
            file.setReadable(true);
            file.setWritable(false);
            System.out.println("File permissions changed.");
 
            // Printing the permissions associated with the
            // file currently
            System.out.println("Executable: "
                               + file.canExecute());
            System.out.println("Readable: "
                               + file.canRead());
            System.out.println("Writable: "
                               + file.canWrite());
        }
 
        // If we reach here, file is not found
        else {
            System.out.println("File not found");
        }
    }
}


Output:

BERJAYA



Previous Article
Next Article

Similar Reads

How to Request Permissions in Android Application?
Starting from Android 6.0 (API 23), users are not asked for permissions at the time of installation rather developers need to request the permissions at the run time. Only the permissions that are defined in the manifest file can be requested at run time. Types of Permissions 1. Install-Time Permissions: If the Android 5.1.1 (API 22) or lower, the
8 min read
Easy Runtime Permissions in Android with Dexter
The Runtime Permission in Android which introduced in Marshmallow and due to these runtime permissions users can grant permission to the app in runtime, also while writing the code for runtime permissions. Sometimes handling the task of requesting permissions becomes so difficult and the developer has to write a huge amount of code. So we will see
7 min read
How to Execute SQL File with Java using File and IO Streams?
In many cases, we often find the need to execute SQL commands on a database using JDBC to load raw data. While there are command-line or GUI interfaces provided by the database vendor, sometimes we may need to manage the database command execution using external software. In this article, we will learn how to execute an SQL file containing thousand
5 min read
How to Convert a Kotlin Source File to a Java Source File in Android?
We use Android Studio to translate our Java code into Kotlin while transitioning from Java to Kotlin. But what if we need to convert a Kotlin file to its Java equivalent? We'll examine how to convert a Kotlin source file to a Java source file in this blog. Let's get this party started. Because of its interoperability with Java, Kotlin grew at an ex
2 min read
java.nio.file.attribute.FileTime Class in Java
The java.nio.file.attribute.FileTime class is used to get a value representing this file's timestamp i.e, the time when this file was last modified, accessed, or created. Class Declaration: public final class FileTime extends Object implements Comparable<FileTime>Methods: MethodDescriptioncompareTo(FileTime other)This method compares the valu
2 min read
java.nio.file.SimpleFileVisitor Class in Java
The java.nio.file.SimpleFileVisitor Class is used to visit all the files in a directory and to re-throw I/O exceptions whenever an I/O error occurs. Class declaration : public class SimpleFileVisitor<T> extends Object implements FileVisitor<T>Constructor: protected SimpleFileVIsitor(): Creates a new object of SimpleFileVisitor class.Met
3 min read
java.nio.file.Paths Class in Java
java.nio.file.Paths class contains static methods for converting path string or URI into Path. Class declaration : public final class Paths extends ObjectMethods: MethodDescriptionget(String first, String... more) This method converts a path string, or a sequence of strings that when joined form a path string, to a Path. get(URI uri) This method co
2 min read
java.nio.file.spi.FileTypeDetector Class in Java
java.nio.file.spi.FileTypeDetector Class extends java.lang.Object Class. FileTypeDetector Class contain method to know about the content type of given file. Class declaration: public abstract class FileTypeDetector extends ObjectConstructor: ConstructorDescriptionprotected FileTypeDetector()It is used the creation of a new object of FileTypeDetecto
2 min read
java.nio.file.LinkPermission Class in Java
The java.nio.file.LinkPermission class handles permissions for link creation operations. The permission allowed by these class are as follows: Permission name What permission allows Risk of granting this permission hard This permission allows adding an existing file to a directory. This operation is also known as creating a hard link. The attacker
3 min read
java.nio.file.FileStore Class in Java
Java.nio.file is a package in java that consists of the FileStore class. FileStore class is a class that provides methods for the purpose of performing some operations on file store. FileStore is a class that extends Object from java.lang package. And few methods the FileStore class can inherit from java.lang.Object package is clone(), equals(), fi
4 min read
java.nio.file.FileSystem class in java
java.nio.file.FileSystem class provides an interface to a file system. The file system acts as a factory for creating different objects like Path, PathMatcher, UserPrincipalLookupService, and WatchService. This object help to access the files and other objects in the file system. Syntax: Class declaration public abstract class FileSystem extends Ob
4 min read
java.nio.file.FileSystems Class in Java
java.nio.file.FileSystems class acts as a factory for creating new file systems. This class provides methods for creating file systems. This file system act as factories for creating different objects like Path, PathMatcher, UserPrincipalLookupService, and WatchService. This object helps to access the files and other objects in the file system. Syn
3 min read
java.nio.file.attribute.AclEntry Class in Java
ACL entries are Examined by this class is validating on the ACL model declared in RFC 3530: Network File System i.e.(NFS) version of 4th Protocol and having four components within it as follows characteristics as follows: This type of component are determining if the entry grants or denies its accessingThe principal component is generally known as
3 min read
Java.io.File Class in Java
Java File class is Java's representation of a file or directory pathname. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. Java File class contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the contents of
6 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java Class File
A Java class file is a file containing Java bytecode and having .class extension that can be executed by JVM. A Java class file is created by a Java compiler from .java files as a result of successful compilation. As we know that a single Java programming language source file (or we can say .java file) may contain one class or more than one class.
5 min read
Size of file on the Internet using Java
To get the size of file from server first you need to connect to the server using URL and HttpURLConnection Class. To get the size of file we use getContentLength() method. As the size of file can be too large we use BigInteger class. You cannot use integer datatype as it can generate an error in case the size of file is greater than 2Gb. To know m
2 min read
Creating a Cell at specific position in Excel file using Java
Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats/ it can be used to create a cell in a Given Excel file at a specific position. Apache POI is an API provided by the Apach
2 min read
Reading a CSV file in Java using OpenCSV
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java lang
7 min read
Writing a CSV file in Java using OpenCSV
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in a column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java la
5 min read
Creating Sheets in Excel File in Java using Apache POI
Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats. For Example, java doesn’t provide built-in support for working with excel files, so we need to look for open-source APIs
3 min read
File getAbsolutePath() method in Java with Examples
The getAbsolutePath() method is a part of File class. This function returns the absolute pathname of the given file object.If the pathname of the file object is absolute then it simply returns the path of the current file object. For Example: if we create a file object using the path as "program.txt", it points to the file present in the same direc
3 min read
File getAbsoluteFile() method in Java with Examples
The getAbsoluteFile() method is a part of File class. This function returns the absolute File object of the given abstract pathname. The absolute file or directory points to the same file or directory as the given File object. For Example: If we create a file object using the path as "program.txt", it points to the file present in the same director
3 min read
Convert byte[] array to File using Java
As we know whenever it comes to writing over a file, write() method of the File class comes into play but here we can not use it in order to convert that byte into a file. In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it
3 min read
File canExecute() method in Java with Examples
The canExecute() function is a part of File class in Java. This function determines whether the program can execute the specified file denoted by the abstract pathname. If the file path exists and the application is allowed to execute the file, this method will return true. Else it will return false. Function signature: public boolean canExecute()
2 min read
File canRead() method in Java with Examples
The canRead()function is a part of the File class in Java. This function determines whether the program can read the file denoted by the abstract pathname. The function returns true if the abstract file path exists and the application is allowed to read the file.Function signature: public boolean canRead() Syntax: file.canRead() Parameters: This me
2 min read
File canWrite() method in Java with examples
The canWrite()function is a part of File class in Java . This function determines whether the program can write the file denoted by the abstract path name.The function returns true if the abstract file path exists and the application is allowed to write the file. Function signature: public boolean canWrite() Syntax: file.canWrite() Parameters: This
2 min read
File getUsableSpace() method in java with examples
The getUsableSpace() function is a part of File class in Java . This function returns the unallocated size of the partition denoted by the abstract pathname, if the pathname does not exist then it returns 0L. This function is more accurate than the getFreeSpace() function as it returns the free space allocated to this virtual machine. This function
2 min read
File renameTo() method in Java with examples
The renameTo() method is a part of File class. The renameTo() function is used to rename the abstract path name of a File to a given path name. The function returns true if the file is renamed else returns false Function Signature: public boolean renameTo(File destination) Syntax: file.renameTo(File destination) Parameters: The function requires Fi
2 min read
File getParentFile() method in Java with Examples
The getParentFile() method is a part of File class. This function returns the Parent file of the given file object. The function returns a File object which contains the Parent file of the given file object. If the abstract path does not contain any Parent file then a null value is returned. Function Signature:public File getParentFile() Function S
2 min read
Article Tags :
Practice Tags :