Java 属性文件的JTextField
我试图将Jtextfield中的输入附加到已设置的测试属性配置文件中。但是,每次尝试追加文本时,我都会收到NullPointerException。我读到Properties API不允许添加/删除/编辑,所以我也尝试了BufferedWriter,但它也不起作用。如果有人知道这样做的方法,我将非常感激 通过JButton追加文本:Java 属性文件的JTextField,java,properties,append,jtextfield,fileinputstream,Java,Properties,Append,Jtextfield,Fileinputstream,我试图将Jtextfield中的输入附加到已设置的测试属性配置文件中。但是,每次尝试追加文本时,我都会收到NullPointerException。我读到Properties API不允许添加/删除/编辑,所以我也尝试了BufferedWriter,但它也不起作用。如果有人知道这样做的方法,我将非常感激 通过JButton追加文本: if (userField.getText().toString().equals("")) { lblNullUser.setV
if (userField.getText().toString().equals("")) {
lblNullUser.setVisible(true);
} else {
lblNullUser.setVisible(false);
}
if(!chckbxRememberUser.isSelected()) {
//To do: go to Lynx
} else {
String user = userField.getText();
c.prop.setProperty("user", user); //null on this line; problem might be the key but not sure how to fix
try {
c.prop.store(c.outputSteam, null);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
配置类:
public String Config() throws IOException{
String result = "";
prop = new Properties();
propFileName = "config.properties";
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
outputSteam = new FileOutputStream("config.properties");
prop.load(inputStream);
if (inputStream == null) {
throw new FileNotFoundException("Config file '" + propFileName + "' not found.");
}
//Date time = new Date(System.currentTimeMillis());
return result;
}
如果键或值为null,作为属性父类的哈希表将抛出NullPointerException
确保键和值都不为null。在您的情况下,要么值为null,要么属性对象本身为null。
添加类似这样的检查以验证和更新属性
String user = userField.getText();
if (user != null && c.prop != null) {
c.prop.setProperty("user", user);
} else {
// Some params are null - log and verify
}
为了避免NullPointer异常,我建议在使用inputStream加载属性之前检查其是否为null
if (inputStream == null) {
throw new FileNotFoundException("Config file '" + propFileName + "' not found.");
}
prop.load(inputStream);
但是,您的整个代码包含更多的潜在问题:
Config是一个构造函数吗?这不是因为它返回一个字符串。用这种方法初始化实例变量是没有意义的。
您不会在任何地方关闭inputStream和outputStream。
在需要输出流之前提前打开它是个坏主意。
不使用getter直接访问另一个类的字段是不好的风格。
...
显示c.prop的来源代码。