Search code examples
javajarrunnablefilenotfoundexceptionfileoutputstream

FileOutputStream inside runnable jar throwing FileNotFoundException if path contains folder


When using a FileOutputStream to Output an Object to a folder inside a runnable jar you will get a FileNotFoundException

example code that will throw FileNotFoundException (whether the directory or file is existing or not):

        ObjectOutputStream wf = new ObjectOutputStream(new FileOutputStream("res/followers.txt"));
        wf.writeObject(crntFollowers);
        wf.flush();
        wf.close();
        writeSettingFollowers(crntFollowers.size());

However when using the same code without adding a 'folder' to the path you will not get a FileNotFoundException but the File wont be created at all

example code that will not throw FileNotFoundException:

        ObjectOutputStream wf = new ObjectOutputStream(new FileOutputStream("followers.txt"));
        wf.writeObject(crntFollowers);
        wf.flush();
        wf.close();
        writeSettingFollowers(crntFollowers.size());

Both code snippets work when compiled in Eclipse but not as a runnable jar, my guess is that it is due to the different pathing but I dont know how to fix it.

So how can I outwrite an Object to a folder inside a runnable jar without getting FileNotFoundException and the file also beeing created?


Solution

  • You are mistaken.

    1. You can't create files inside running JARs with FileOutputStream or indeed in any other way shape or form.
    2. The file will be created if there is no exception, but in the current working directory, not in the JAR file.