Menu
Topics Index
...
`

FilePermissionsDemo - Java Example Program


FilePermissionsDemo
import java.io.*;

class FileOperationsDemo
{
    public static void main(String[] args) throws IOException
    {
        File sampleFile = new File("E:JavaPrograms\\FolderOne\\sampleFile.txt");
        if(sampleFile.createNewFile())                     // LINE A
            System.out.println("File created.");
        else
            System.out.println("File not created.");
        
        System.out.println("Default permissions for a newly created file.");
        System.out.println("IsFile        : " + sampleFile.isFile()); // LINE B
        System.out.println("CanRead    : " + sampleFile.canRead());    // LINE C
        System.out.println("CanWrite   : " + sampleFile.canWrite());   // LINE D
        System.out.println("CanExecute : " + sampleFile.canExecute()); // LINE E
    
        System.out.println("Changing file permissions.");
         // LINE F                                  
        System.out.println("Can set to non readable   : " + sampleFile.setReadable(false));
        // LINE G                                
        System.out.println("Can set to non writable   : " + sampleFile.setWritable(false));
        // LINE H                                
        System.out.println("Can set to non Executable : " + sampleFile.setExecutable(false));
    }
}
OUTPUT

File created.
Default permissions for a newly created file.
IsFile        : true
CanRead    : true
CanWrite   : false
CanExecute : true
Changing file permissions.
Can set to non readable   : false
Can set to non writable   : true
Can set to non Executable : false

DESCRIPTION

At LINE A we have created a sampleFile.
At LINE B we are checking whether sampleFile is a File or not.
At LINE C we are checking whether sampleFile is readable.
At LINE D we are checking whether sampleFile is writable.
At LINE E we are checking whether sampleFile is executable.
At LINE F we are checking whether we can set sampleFile to non readable.
At LINE G we are checking whether we can set sampleFile to non writable.
At LINE F we are checking whether we can set sampleFile to non executable.

THINGS TO TRY
  • Find the path of sampleFile using getPath method.
  • Delete sampleFile file.

© meritcampus 2019

All Rights Reserved.

Open In App