I am trying to create a file on the filesystem, but I keep getting this exception:
java.io.IOException: No such file or directory
I have an
If the directory ../.foo/bar/
doesn't exist, you can't create a file there, so make sure you create the directory first.
Try something like this:
File f = new File("somedirname1/somedirname2/somefilename");
if (!f.getParentFile().exists())
f.getParentFile().mkdirs();
if (!f.exists())
f.createNewFile();
Print the full file name out or step through in a debugger. When I get confused by errors like this, it means that my assumptions and expectations don't match reality. Make sure you can see what the path is; it'll help you figure out where you've gone wrong.
You may want to use Apache Commons IO
's FileUtils.openOutputStream(File) method. It has good Exception messages when something went wrong and also creates necessary parent dirs. If everything was right then you directly get your OutputStream - very neat.
If you just want to touch
the file then use FileUtils.touch(File)
instead.
Try with
f.mkdirs() then createNewFile()
File.isFile()
is false
if the file / directory does not exist, so you can't use it to test whether you're trying to create a directory. But that's not the first issue here.
The issue is that the intermediate directories don't exist. You want to call f.mkdirs()
first.
Be careful with permissions, it is problably you don't have some of them. You can see it in settings -> apps -> name of the application -> permissions -> active if not.