Search code examples
javaiofilenotfoundexceptionfileinputstream

java.io.FileNotFoundException when creating FileInputStream


Getting an error when trying to open a FileInputStream to load Map from file with .ser extension.

Constructor where I create new File and invoke method that loads map from file:

protected DriveatorImpl() {
    accounts = new ConcurrentHashMap<String, Client>();
    db = new File("database.ser"); // oddly this does not create a file if one does not exist
    loadDB(); 
}

@SuppressWarnings("unchecked")
private void loadDB() {
    try {
        fileIn = new FileInputStream(db);
        in = new ObjectInputStream(fileIn);
        accounts = (Map<String, Client>) in.readObject();
        in.close();
        fileIn.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

I've tried to create file manually and put it in same package with class, but it does not help. What's going on?!

Thank You!


Solution

  • You provide a relative path for the file. That means program will look for the file relative to the working directory.

    Depending on how you run the program it will be the directory you run it from (if run from Shell/Cmd) or whatever is configured in the project settings (if run from the IDE). For the latter, it depends on the IDE but usually it's the project root directory.

    More info on working directory: https://en.wikipedia.org/wiki/Working_directory
    More info on relative path: https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths

    Regarding creation of the file, it would create non-existing file if you were to write to it. When you read it, it expects it to exist. That means you have to create empty file (if one does not exist) before reading or simply treat exception as empty content.