java.io.FileNotFoundException when creating FileInputStream

做~自己de王妃 提交于 2019-12-04 06:43:28

问题


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!


回答1:


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.




回答2:


  • The path to the file you have given might be wrong for IDE it can take relative path but from the command line, it will take the absolute path.


来源:https://stackoverflow.com/questions/41628486/java-io-filenotfoundexception-when-creating-fileinputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!