In Java, file permissions are very OS specific: NTFS (windows) and FAT/FAT32, all have different kind of file permissions. Java comes with some generic file permission to deal with it.
Check if the file permission allow :
file.canExecute(); – return true, file is executable; false is not.
file.canWrite(); – return true, file is writable; false is not.
file.canRead(); – return true, file is readable; false is not.
Set the file permission :
file.setExecutable(boolean); – true, allow execute operations; false to
disallow it.
file.setReadable(boolean); – true, allow read operations; false to
disallow it.
file.setWritable(boolean); – true, allow write operations; false to
disallow it.
Java IO classes do not have ready method for it, but you can use the following :
File permission example:
package javatest.file; import java.io.File; import java.io.IOException; public class FilePermissionExample { public static void main( String[] args ) { try { File file = new File("/javatest/myjava.td"); if(file.exists()){ System.out.println("Is Execute allow : " + file.canExecute()); System.out.println("Is Write allow : " + file.canWrite()); System.out.println("Is Read allow : " + file.canRead()); } file.setExecutable(false); file.setReadable(false); file.setWritable(false); System.out.println("Is Execute allow : " + file.canExecute()); System.out.println("Is Write allow : " + file.canWrite()); System.out.println("Is Read allow : " + file.canRead()); if (file.createNewFile()){ System.out.println("new File is created!"); }else{ System.out.println("this File already exists."); } } catch (IOException e) { e.printStackTrace();}}} |
Core Java Interview Questions
Object Oriented Programming(OOP) Questions and Answers
Collections Interview Questions
Java Exceptions Interview Questions
Java Threads Interview Questions
Collection framework in java interview questions
oops concepts with example in java
Java Serialization Interview Questions
Top 20 Core Java Interview Questions with Answers
String Interview Question in java With Example
synchronization interview questions
Java Reflection Interview question
Java Executor Framework (JDK 1.5) Interview Questions
JDK 1.7 interview Questations and Answers
Java I/O interview question with example