[英]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的原因。
如果您確實進行了初始化,請提供代碼!
可能是您的propDef
和propLim
為null,並且在調用propDef.load(new FileInputStream(def));
您會獲得NPE,因為load
方法是實例方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.