After compiling the following code in Eclipse using a Mac:
import java.io.*;
public class Filer{
public static void main(String[] args) throws IOException{
File f1;
f1 = new File("/System/file.txt");
if(!f1.exists()){
f1.createNewFile();
}
}
}
I get an error:
Exception in thread "main" java.io.IOException: Permission denied
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)
at Filer.main(Filer.java:11)
Can anyone tell me why that is? Is there any way to change the permissions? And if I were to compile this as a .jar file and send it to someone, would that person have the correct permissions?
This error occurs when the user does not have the privileges to make edits to a file. Root has access to all files and folders and can make any edits. Other users, however, may not be allowed to make such edits. Remember that only root or users with Sudo privileges can change permissions for files and folders.
setWritable() − This method is used to set the write permissions to the file represented by the current (File) object. setReadable() − This method is used to set the read permissions to the file represented by the current (File) object.
If you receive an error telling you that you do not have permissions to create a directory or to write a file to a directory, this is likely an indication that your script is attempting to write to a directory that you do not own.
A permission represents access to a system resource. In order for a resource access to be allowed for an applet (or an application running with a security manager), the corresponding permission must be explicitly granted to the code attempting the access.
Can anyone tell me why that is?
Your user doesn't have permission to create a file in that directory.
Is there any way to change the permissions?
The same way you would change the permissions of any directory.
In Java 7+
Files.setPosixFilePermisions(f1.toPath(),
EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ, GROUP_EXECUTE));
And if I were to compile this as a .jar file and send it to someone, would that person have the correct permissions?
I suspect the correct permissions for a directory called /System
is that you NOT have write access.
Is there any reason not to use the home directory or the current working directory?
Only users with special privileges are allowed to write in the System directory.
Normal users can only write in their home directory
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With