繁体   English   中英

java-读取.properties文件并将其存储在properties对象中

[英]java - reading .properties file and storing it in properties object

如标题中所述,我必须在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();

您从未初始化propDef,这就是为什么您得到NullPointerException的原因。

如果您确实进行了初始化,请提供代码!

可能是您的propDefpropLim为null,并且在调用propDef.load(new FileInputStream(def)); 您会获得NPE,因为load方法是实例方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM