Cannot make file java.io.IOException: No such file or directory

Shervin Asgari picture Shervin Asgari · Sep 19, 2011 · Viewed 105k times · Source

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 existing directory, and I am trying to write a file to that directory.

// I have also tried this below, but get same error
// new File(System.getProperty("user.home") + "/.foo/bar/" + fileName);

File f = new File(System.getProperty("user.home") + "/.foo/bar/", fileName);

if (f.exists() && !f.canWrite())
        throw new IOException("Kan ikke skrive til filsystemet " + f.getAbsolutePath());

if (!f.isFile()) {
    f.createNewFile(); // Exception here
} else {
    f.setLastModified(System.currentTimeMillis());
}

Getting exception:

java.io.IOException: No such file or directory
  at java.io.UnixFileSystem.createFileExclusively(Native Method)
  at java.io.File.createNewFile(File.java:883)`

I have write permission to the path, however the file isn't created.

Answer

Bohemian picture Bohemian · Sep 19, 2011

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();