w3resource

Java: Check if a file or directory has read and write permission


4. Check Read and Write Permissions

Write a Java program to check if a file or directory has read and write permissions.

Sample Solution:

Java Code:

import java.io.File;
public class Exercise4 {
       public static void main(String[] args) {
        // Create a File object
        File my_file_dir = new File("/home/students/abc.txt");
         if (my_file_dir.canWrite()) 
           {
            System.out.println(my_file_dir.getAbsolutePath() + " can write.\n");
           } 
         else
          {
            System.out.println(my_file_dir.getAbsolutePath() + " cannot write.\n");
          }
         if (my_file_dir.canRead()) 
           {
            System.out.println(my_file_dir.getAbsolutePath() + " can read.\n");
           } 
         else
          {
            System.out.println(my_file_dir.getAbsolutePath() + " cannot read.\n");
          }  
      }
  }
  

Sample Output:

/home/students/abc.txt can write.                                                                                    
/home/students/abc.txt can read.

Flowchart:

Flowchart: Check if a file or directory has read and write permission


For more Practice: Solve these Related Problems:

  • Write a Java program to check if a file or directory has both read and write permissions using Java NIO.
  • Write a Java program to determine if a given file is readable, writable, and executable by the current user.
  • Write a Java program to verify file permissions for a set of files in a directory and output those that lack proper access.
  • Write a Java program to simulate permission checks by attempting to read and write a temporary file in a specified directory.

Go to:


PREV : Check Path Exists.
NEXT : Check File or Directory.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.