Permission denied: file creation in Java

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 message:

  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 someone tell me why this is so? Is there a way to change permissions? And if I have to compile this as a .jar file and send it to someone, will this person have the correct permissions?

+6
source share
2 answers

Can someone tell me why this is?

Your user does not have permission to create a file in this directory.

Is there a way to change permissions?

Similarly, 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 that the correct permissions for the directory named /System are that you do not have write access.

Is there a reason not to use the home directory or current working directory?

+8
source

Only users with special privileges are allowed to write to the system directory.

Ordinary users can only write in their home directory

+2
source

All Articles