JTextField到Properties文件

时间:2014-10-04 05:53:03

标签: java properties append jtextfield fileinputstream

我正在尝试将Jtextfield中的输入附加到我已设置的测试属性配置文件中。但是,每次我尝试附加文本时,我都会收到NullPointerException。我已经读过Properties API不允许添加/删除/编辑所以我也尝试过BufferedWriter,但它也不起作用。如果有人知道这样做的方法,我将非常感激。

通过JButton附加文本:

 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;
}

2 个答案:

答案 0 :(得分:0)

Hashtable如果键或值为null,则Properties的父类将抛出NullPointerException

确保密钥和值都不是null。在您的情况下,value为空或properties对象本身为空。 添加这样的支票以验证和更新属性。

String user = userField.getText();
if (user != null && c.prop != null) {
  c.prop.setProperty("user", user);
} else {
  // Some params are null - log and verify
}

答案 1 :(得分:0)

为了避免NullPointer异常,我建议在使用它加载属性之前检查inputStream是否为null。

if (inputStream == null) {
  throw new FileNotFoundException("Config file '" + propFileName + "' not found.");
}
prop.load(inputStream);

但是,您的整个代码更容易出现问题:

  • Config()是构造函数吗?它不是因为它返回一个String。以这种方式初始化实例变量是没有意义的。
  • 您并未在任何地方关闭inputStream和outputStream。
  • 提前打开outputStream(在需要它之前)是一个坏主意。
  • 直接访问另一个类的字段(没有getter)是不好的风格。
  • ...