创建FileInputStream时出现java.io.FileNotFoundException [英] java.io.FileNotFoundException when creating FileInputStream

查看:2416
本文介绍了创建FileInputStream时出现java.io.FileNotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试打开FileInputStream以从.ser扩展名的文件加载Map时出错。

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

构造函数,我在其中创建新文件并调用从文件加载地图的方法:

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?!

谢谢!

推荐答案

你提供文件的相对路径。这意味着程序将查找相​​对于工作目录的文件。

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

根据您运行程序的方式,它将是您运行它的目录(如果从Shell运行) / Cmd)或项目设置中配置的任何内容(如果从IDE运行)。对于后者,它取决于IDE,但通常是项目根目录。

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.

有关工作目录的更多信息: https://en.wikipedia.org/wiki/Working_directory

关于相对路径的更多信息: https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths

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.

这篇关于创建FileInputStream时出现java.io.FileNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆