Java I/O – Check file permission and Set file permission




Java Tutorial for Beginners
Java Tutorial for Beginners

In this Lesson we will learn how to check the permissions of a particular file in java. Also we will see how to set the permissions in java.

For Checking the File Permissions use:

  • canExecute() : true if and only if the abstract pathname exists and the application is allowed to execute the file
  • canWrite() : 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.
  • canRead() : true if and only if the file specified by this abstract pathname exists and can be read by the application false otherwise

For Setting the File Permissions use:

  • setExecutable() :  If true, sets the access permission to allow execute operations; if false to disallow execute operations
  • setWritable() :  If true, sets the access permission to allow write operations; if false to disallow write operations
  • setReadable() :  If true, sets the access permission to allow read operations; if false to disallow read operations
/**
 * Created by codebind.com.
 */
import java.io.File;
public class Sample {
    public static void main(String[] args) {
        File myFile = new File("C:" + File.separator + "jdk" + File.separator, "FileName.java");
        System.out.println("is File : " +myFile.isFile());
        System.out.println("is Hidden : " +myFile.isHidden());
        if(myFile.exists()) {
            System.out.println("Can File Execute : " + myFile.canExecute());
            System.out.println("Can File Write : " + myFile.canWrite());
            System.out.println("Can File Read : " + myFile.canRead());
        }

        myFile.setExecutable(false);  // returns true if and only if the operation succeeded.
        myFile.setReadable(false);    // returns true if and only if the operation succeeded.
        myFile.setWritable(false);    // returns true if and only if the operation succeeded.


        System.out.println("Can File Execute : " + myFile.canExecute());
        System.out.println("Can File Write : " + myFile.canWrite());
        System.out.println("Can File Read : " + myFile.canRead());

    }
}

 

OUTPUT:
is File : true
is Hidden : false
Can File Execute : true
Can File Write : true
Can File Read : true
Can File Execute : true
Can File Write : false
Can File Read : true


Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Be the first to comment

Leave a Reply

Your email address will not be published.


*