当我在Eclipse中使用我的程序时,一切都运行良好,JSON文件在启动之间保存。当我将项目导出到Runnable Jar文件时,问题就出现了,保存JSON文件根本不再有效。我仍然可以从文件中读取,但它不能保存它。
这是我写的“写/保存”代码。
/*
* Write to character JSON file
*/
public void saveCharacterInfo() {
JSONObject obj = JSONUtils.getJSONObjectFromFile("/character.json");
obj.put("day", c.getDay());
obj.put("name", c.getCharName());
obj.put("hp", c.getCharHp());
obj.put("maxHp", c.getCharHpMax());
obj.put("armor", c.getCharArmor());
obj.put("speed", c.getCharSpeed());
obj.put("strength", c.getCharStrength());
obj.put("money", c.getCharMoney());
obj.put("food", c.getCharFood());
obj.put("maxFood", c.getCharMaxFood());
obj.put("morale", c.getCharMorale());
obj.put("bait", c.getCharBait());
try {
URL resourceUrl = getClass().getResource("/character.json");
File file = new File(resourceUrl.toURI());
FileWriter writer = new FileWriter(file);
writer.write(obj.toString());
writer.flush();
writer.close();
} catch (Exception e) {
}
}
答案 0 :(得分:0)
由于Eclipse之外既没有bin也没有文件本身尚未创建,你必须首先创建它,如果以前有文件,因为我们要覆盖它,我们使用delete方法在创建它之前。所以整个变化写在这里:
public void saveCharacterInfo() {
JSONObject obj = JSONUtils.getJSONObjectFromFile("/character.json");
obj.put("day", c.getDay());
obj.put("name", c.getCharName());
obj.put("hp", c.getCharHp());
obj.put("maxHp", c.getCharHpMax());
obj.put("armor", c.getCharArmor());
obj.put("speed", c.getCharSpeed());
obj.put("strength", c.getCharStrength());
obj.put("money", c.getCharMoney());
obj.put("food", c.getCharFood());
obj.put("maxFood", c.getCharMaxFood());
obj.put("morale", c.getCharMorale());
obj.put("bait", c.getCharBait());
try {
URL resourceUrl = getClass().getResource("/character.json");
File file = new File(resourceUrl.toURI());
file.getParentFile().mkdirs();
file.delete();
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(obj.toString());
writer.flush();
writer.close();
} catch (Exception e) {
}
}
我测试过它,让jar创建新文件夹的方法是从windows命令控制台执行它:
java -jar jarName.jar
或者在同一文件夹上创建一个bat文件。