Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - file.createNewFile() IOException "No such file or directory" [closed]

While coding Java had this problem: file.createNewFile() throws IOException "No such file or directory". Checked out other answers but nothing seems to be helpful. Any ideas?..

like image 719
Mugi4ok Avatar asked Oct 07 '14 15:10

Mugi4ok


4 Answers

It's likely that you're trying to create the file in a directory that does not exist.

Use mkdirs() to create any missing parent directories first.

File file = new File("foo/bar.txt")
file.getParentFile().mkdirs();
file.createNewFile();
like image 155
kapex Avatar answered Oct 04 '22 01:10

kapex


I think you are trying to create a new file in a directory that does not exist. The whole path needs to exist, only the file can be non-existent.

like image 24
Juru Avatar answered Oct 03 '22 23:10

Juru


Oh, I got it. It appeared to be more Windows problem than Java. Actually, even with UAC disabled random app still have no rights to write something on C: (or whatever it is on your system) on Win8. Never got this problem using Win7 though. Using "Run as Administrator" on IDE does not help as it doesn't give such rights to Java compiler. So, I just moved my projects folder to other disk. Also, you can change access rights, but it was easier for me. And yes, nobody mentioned about a chance of this happening in other questions, so I hope it'll be helpful to anyone.

like image 27
Mugi4ok Avatar answered Oct 04 '22 01:10

Mugi4ok


You need to create the Folder first. createNewFile cannot create them:

File folderFile = new File("c:\\this\\folder\\has\\subfolders");
folderFile.mkdirs();

File myFile = new File(folderFile,"myfile.txt");
myFile.createNewFile();
like image 27
dube Avatar answered Oct 03 '22 23:10

dube