【问题标题】:java - reading .properties file and storing it in properties objectjava - 读取 .properties 文件并将其存储在属性对象中
【发布时间】:2016-05-04 12:01:49
【问题描述】:

如标题中所述,我必须在 java 中读取 .properties 文件并将其存储在 Properties 对象中。我使用来自 java swing 的jFileChooser 来获取实际工作的文件,然后我将文件作为调用参数传递到新窗口,然后我使用load() 方法将其存储在Properties 对象中,但我得到java.lang.NullPointerException 错误。我希望我清楚地试图解释它。

这是代码:

    public void actionPerformed(ActionEvent e3) { //when button is pressed
            JFileChooser fc2 = new JFileChooser (new File("C:\\Users\\Ciurga\\workspace\\PropertiesManager"));
            fc2.setDialogTitle("Load Default Values File");
            fc2.setFileFilter(new FileTypeFilter(".properties", "Properties File"));
            int result = fc2.showOpenDialog(null);
            if(result == JFileChooser.APPROVE_OPTION){
                df = fc2.getSelectedFile(); //getting selected file and storing it in "df" which will be passed as calling argument     
                defaultNameTextField.setText(df.getName());
            }
        }

这就是我将文件传递到另一个窗口的方式:

public void actionPerformed(ActionEvent e1) {
            FormWindow w1 = new FormWindow (df, lf); //when button is pressed, create new window passing the files i got with jFileChooser
        }

这就是我尝试将其存储在 Properties 对象中的方式:

private static Properties propDef;
private static Properties propLim; 

private void run(File def, File lim) {
    try {
        propDef.load(new FileInputStream(def));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        propLim.load(new FileInputStream(lim));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(propDef.getProperty("name"));

}

谢谢你们,正如你们所说,我只需要初始化它,现在它似乎可以正常工作,这是一个简单的错误,但我实际上是 java 的初学者。 这是我改变的:

private static Properties propDef = new Properties();
private static Properties propLim = new Properties();

【问题讨论】:

  • 你初始化propDefpropLim了吗?如果不是这样,他们是 null ,并且在他们身上调用 load 会给你NullPointerException

标签: java swing properties-file


【解决方案1】:

你从未初始化过 propDef,这就是你得到 NullPointerException 的原因。

如果你确实初始化了,请提供代码!

【讨论】:

    【解决方案2】:

    您的propDefpropLim 可能为空,当您调用propDef.load(new FileInputStream(def)); 时,您会得到一个NPE,因为load 方法是实例方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-24
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 2013-11-19
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多