【问题标题】:When I create a file through code I can't see it in eclipse当我通过代码创建文件时,我在 eclipse 中看不到它
【发布时间】:2022-03-10 01:58:23
【问题描述】:

所以我正在用java制作一个游戏引擎,它有两个部分:编辑器和游戏引擎本身。 在编辑器中,我序列化 Scene 对象并将它们写入 .scene 文件以供引擎读取,但该文件没有显示在 eclipse 中,我可以在文件资源管理器中看到它,因此它被创建了。有一段时间我没有注意,因为我仍然可以使用File 类读取文件。但是后来我尝试将它导出到一个可运行的 jar 文件中并且构建不起作用,所以我尝试使用 getClass().getResource("path") 并且遇到了问题,因为我知道该文件没有被添加到构建路径中,甚至出于某种奇怪的原因你它在 src 文件夹中,我可以通过编程方式将文件添加到构建路径还是需要做其他事情?

这是一些代码:

public File createSceneFile(String path) {
    try {
        File file = new File(path);
        
        if(file.createNewFile()) {
            FileOutputStream fileStream = new FileOutputStream(path);
            ObjectOutputStream os = new ObjectOutputStream(fileStream);
            os.writeObject(scene);
            os.close();
        }
            
        return file;
    }catch(IOException e) {
        e.printStackTrace();
        return null;
    }
}
    
public File updateScene(String path) {
    try {
        FileOutputStream fileStream = new FileOutputStream(path);
        ObjectOutputStream os = new ObjectOutputStream(fileStream);
        os.writeObject(scene);
        os.close();
        
        return new File(path);
    }catch(IOException e) {
        e.printStackTrace();
        return null;
    }
}

读取 .scene 文件的代码:

public Scene getScene(URL url) {
    try {
        InputStream inStream = url.openStream();
        ObjectInputStream ois = new ObjectInputStream(inStream);
        Scene s = null;
        try {
            s = (Scene)ois.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        ois.close();
        
        s.instantiation = this;
        return s;
    }catch(IOException e) {
        e.printStackTrace();
        return null;
    }
}

提前致谢

【问题讨论】:

  • 使用“文件 > 刷新”让 Eclipse 获取已添加到工作区的文件。
  • 您使用的是 Maven 或 Gradle 之类的构建工具吗?在这种情况下,将文件放在 src 目录中的确切位置很重要。通常他们应该去src/main/resources 并且你的构建应该在那里拾取它们然后放入jar文件的根目录中。
  • @greg-449 由于某种原因它不起作用
  • @Thomas 不,我使用默认的 java 编译器
  • 所以您只是使用普通的javac 命令还是让Eclipse 进行构建和打包?

标签: java eclipse file build jar


【解决方案1】:

您很可能需要刷新项目,以便 Eclipse 看到新文件已添加。选择项目并按 F5。

【讨论】:

    猜你喜欢
    • 2012-08-26
    • 2020-12-28
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    相关资源
    最近更新 更多