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

120,072

Solution 1

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.

Solution 2

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

Solution 3

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.

Permissions app

Solution 4

Try with

f.mkdirs() then createNewFile()

Solution 5

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.

Share:
120,072
Shervin Asgari
Author by

Shervin Asgari

Senior Java Developer and Architect Trekkie Linux Ubuntu User My private homepage is here My Civilization Boardgame from Fantasy Flight games implementation is here and if you want to follow me on twitter, I am @ShervinAsgari

Updated on June 09, 2021

Comments

  • Shervin Asgari
    Shervin Asgari almost 3 years

    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.