您好,我使用 Eclipse 用 Java 编写了一个游戏,我通过一个读取/写入配置 txt 文件的类来管理首选项。 当我从 eclipse 运行它时,一切正常,但是当我从我创建的 jar 运行它时,读取和写入都不起作用。 我设法使用 getResourceAsStream 解决了读取问题,但我不知道如何解决写入问题。 这是我用来读取文件的代码:
try {
InputStream is = getClass().getResourceAsStream("/res/configuration.txt");
Properties properties = new Properties();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
properties.load(br);
br.close();
}
和 properties.getProperty 获取值。 在 Eclipse 和 jar 中工作。
这是我尝试编写文件的代码:
try {
properties.setProperty("playerColor", value);
FileOutputStream fos = new FileOutputStream("/res/configuration.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos);
properties.store(osw, null);
osw.close();
}
在任何情况下都不起作用,它说找不到文件。
我该如何解决?另外,我必须在代码中使用类 Properties。
谢谢
更多信息
我使用两个 csv 文件来保存记录和游戏,以及一个 txt 文件用于配置,它们位于“res”包中,方式如下:
Project Folder
--- classpath
--- bin
--- src
--- project
--- res
--- records.csv
--- save.csv
--- configuration.txt
最佳答案
好吧,首先,jar 是一个存档,不能更改。 所以正确的解决方案是写入外部源。 您可以创建一个文件夹并将游戏中的所有数据(统计数据、保存文件等)放入该文件夹
关于java - 从 jar 里写一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31770493/