This example shows how to set permission on a file in Java.
File class provides various methods like setExecutable, setReadable, setWritable, etc to change the permissions of any file in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import java.io.File; import java.io.IOException; public class FilePermissionExample { public static void main(String[] args) { try { File file = new File("/mydir/shellscript.sh"); 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("File is created!"); } else { System.out.println("File already exists."); } } catch (IOException e) { e.printStackTrace(); } } } |