【发布时间】: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();
【问题讨论】:
-
你初始化
propDef和propLim了吗?如果不是这样,他们是null,并且在他们身上调用load会给你NullPointerException
标签: java swing properties-file