Question

I have the following existing directory structure on my file system (Ubuntu 12.04 desktop using ext4):

/
    home/
        myuser/
            .myapp/
                logs/
                    myapp.log
                data/
                lib/

...and the following Java code:

try {
    // If no such file exists, create it and write zero (0) to it.
    if(!myFile.exists()) {
        System.out.println("myFile is: " + myFile.getAbsolutePath());
        myFile.createNewFile();
        myFileWriter.write("0"); // Configured to write to myFile
    }
} catch(IOException ioExc) {
    logger.error(ExceptionUtils.getStackTrace(ioExc));
    throw new RuntimeException(ioExc);
}

...that is throwing the following exception:

myFile is: /home/myuser/.myapp/data/replay/Loader-0-replay.log
java.lang.RuntimeException: java.io.IOException: No such file or directory
    at net.myuser.myapp.tools.myapp.Loader.<init>(Loader.java:69)
    at net.myuser.myapp.tools.myapp.MyAppTool.loadWords(MyAppTool.java:125)
    at net.myuser.myapp.tools.myapp.MyAppTool.run(MyAppTool.java:65)
    at net.myuser.myapp.tools.myapp.MyAppTool.main(MyAppTool.java:41)
Caused by: java.io.IOException: No such file or directory
    at java.io.UnixFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:900)
    at net.myuser.myapp.tools.myapp.Loader.<init>(Loader.java:62)
    ... 3 more

What is going on here? It says "No such file or directory", but isn't that what createNewFile() is supposed to do for me? Thanks in advance!

Was it helpful?

Solution 2

You need to create the folder /home/myuser/.myapp/data/replay before you create the file.

You could try something like

if (!myFile.exists()) {
    System.out.println("myFile is: " + myFile.getAbsolutePath());
    if (!myFile.getParentFile().exists()) {
        myFile.getParentFile().mkdirs();
    }
    myFile.createNewFile();
    myFileWriter.write("0"); // Configured to write to myFile
}

Check the reference:

OTHER TIPS

/home/myuser/.myapp/data/replay/Loader-0-replay.log

I don't see 'replay' in the directory listing you gave.

Try getting the parent File from myFile and then calling File.mkdirs().

try following code:

try {
    // If no such file exists, create it and write zero (0) to it.
    if(!myFile.exists()) {
        System.out.println("myFile is: " + myFile.getAbsolutePath());
        if(!myFile.getParentFile().exists())myFile.getParentFile().mkdirs();
        myFile.createNewFile();
        myFileWriter.write("0"); // Configured to write to myFile
    }
} catch(IOException ioExc) {
    logger.error(ExceptionUtils.getStackTrace(ioExc));
    throw new RuntimeException(ioExc);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top