java.io.FileNotFoundException 创建 FileInputStream 时

java.io.FileNotFoundException when creating FileInputStream

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

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

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();
    }
}

我尝试手动创建文件并将其与 class 放在同一个包中,但没有帮助。怎么回事?!

谢谢!

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

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

有关工作目录的更多信息:https://en.wikipedia.org/wiki/Working_directory
有关相对路径的更多信息:https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths

关于文件的创建,如果您要写入文件,它将创建 non-existing 文件。当您阅读它时,它希望它存在。这意味着您必须在读取之前创建空文件(如果不存在的话)或将异常视为 empty content.

  • 您提供的文件路径对于 IDE 可能是错误的,可能需要 relative path but from the command line, it will take the absolute path