如果它不存在,我试图向config.properties添加一个新属性。有没有办法做到这一点?如果为null,则将属性添加到属性文件
我目前的配置类看起来是这样的:
package com.template;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
public class Config {
static File folder = new File(System.getProperty("user.home") + "/Documents/Electrocode Productions/template");
public static void add() {
if(!folder.exists()) {
try {
folder.mkdirs();
} catch(SecurityException e) {
Log.error(e);
}
}
Properties config = new Properties();
OutputStream output = null;
Path filePath = Paths.get(folder + "/config.properties");
if(!(filePath == null)) {
try {
output = new FileOutputStream(folder + "/config.properties");
config.setProperty("log", "true");
config.store(output, null);
} catch(IOException e) {
Log.error(e);
} finally {
if(output !=null) {
try {
output.close();
} catch(IOException e) {
Log.error(e);
}
}
}
}
}
public static String get(String value) {
Properties config = new Properties();
InputStream input = null;
try {
input = new FileInputStream(folder + "/config.properties");
config.load(input);
} catch(IOException e) {
Log.error(e);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return config.getProperty(value).trim();
}
}
这是工作,因为它不会覆盖该文件,如果您编辑它,但如果你删除的条目,你需要彻底删除整个文件重新添加该条目。
我的最终目标是能够关闭程序,编辑配置文件,然后用新参数重新打开配置文件,但是如果删除参数,它不会因程序而崩溃,因为它依赖于从配置文件的答案。 (我希望这是有道理的,它基本上像大多数电子游戏)。
这不是非常清楚。你能构建一个[最小测试用例](http://stackoverflow.com/help/mcve)来说明吗? –
@Oliver发现问题只是我无法“返回null”我不得不改变它以“不知道”返回“;”然后使用get(value).equals(“unknow”)而不是.equals(null)。谢谢你试图帮助我! – BudSkywalker