Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

java.io.IOException: Permission denied  RSS feed

 
moo jackie
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java.io.IOException: Permission denied
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)
at IOtest.FIle_1.main(FIle_1.java:25)



import java.io.File;

public class FIle_1 {

public static void main(String[] args) {

String fileName=File.separator+"hello.txt";
File f=new File(fileName);
if(!f.exists()){
try{
f.createNewFile();
}catch(Exception e){
e.printStackTrace();
}
}
else{
System.out.println("hi");
}

the file path is wrong?
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Most likely. What's "File.separator+" doing there?
 
moo jackie
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I write another code:

and output:
java.io.IOException: No such file or directory

at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)
at IOtest.FIle_1.main(FIle_1.java:22)

code:
public static void main(String[] args) {
File fDir=new File(File.separator+"file_test");
File file1=new File(fDir,"file1.txt");
if(fDir.exists()){
System.out.println(fDir.getPath());

}else{
fDir.mkdir();
}
if(file1.exists()){
System.out.println(file1.getPath());
file1.delete();
}else{
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}

}
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

You're trying to create files /hello.txt /test_file. The leading slash means you want to put them in the root of your file system. From the exception I see that you are using a Linux or UNIX file system (perhaps Mac OS even). The thing is, on Linux and UNIX systems, not every user can write to any location. Usually all users have only access to their own home folder, and the /tmp folder, with the exception of the root user who can do anything he wants on the system.

So, if you want to write to the root of the file system (which you really really really shouldn't!) you'll need to run your code as a user who has more rights. On Ubuntu you need to put sudo before the command, e.g. sudo java IOTest.File_1, and that will still fail if you're not allowed to run sudo.

And could you please UseCodeTags next time?
 
moo jackie
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks.I get it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!