【问题标题】:IntelliJ IDE - FileNotFound exception from root project directoryIntelliJ IDE - 根项目目录中的 FileNotFound 异常
【发布时间】:2018-05-03 06:47:55
【问题描述】:

我使用 ObjectOutputStream 将对象写入与项目的 .iml 文件位于同一目录中的文件。该文件存在。出于某种原因,我无法使用 FileInputStream 读取它。我在第 2 行收到 FileNotFound 异常。 我的代码如下:

File sceneFile=new File("scene.dodge");
FileInputStream fin=new FileInputStream(sceneFile);
ObjectInputStream in=new ObjectInputStream(fin);
return (Scene)(in.readObject());

我已确定文件 scene.dodge 位于项目根目录中。有什么建议?我试过搞乱编译器资源模式,但我不知道这是否会做任何事情。我简直被难住了。

【问题讨论】:

    标签: java intellij-idea fileinputstream


    【解决方案1】:

    要从当前目录读取文件,您需要使用ClassLoader# getResource method。 像这样加载文件

    URL dodgeSceneURL = classLoader.getResource("scene.dodge");
    File sceneFile = new File(dodgeSceneURL.toURI());
    FileInputStream fin = new FileInputStream(sceneFile);
    

    【讨论】:

    • 我试过了: URL sceneURL=Scene.class.getClassLoader().getResource(path);由于某种原因,这仍然给出了一个空指针异常
    • 类加载器在哪里实例化?恐怕我根本不明白这一点。
    • @TinFellow this.getClass().getClassLoader() 这就是你获得类加载器的方式,我没有发布整个代码,因为这不相关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 2018-12-19
    相关资源
    最近更新 更多