我目前正在開發一個項目,並希望將一個對象保存到ObjectOutputStream
的文件中,並將其保存到用戶在JFileChooser
幫助下選擇的位置。但該對象始終保存到程序的根目錄中,並保存到名爲「null」(%ProjectDirectory%/null
)的文件中。JFileChooser的filePath爲空
這裏是我的方法saveObjects
,從而節省對象文件的LinkedList
:
public void saveObjects(String filePath) {
try {
FileOutputStream os = new FileOutputStream(filePath);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(oceanObjects);
oos.close();
os.close();
} catch(IOException e) {
System.err.println(e);
}
}
該指令要求與filepath
作爲參數(filePath
方法saveObject
是一個字符串,我已經嘗試過使用文件)
saveObjects(view.getFilePath());
view
是OceanLifeView
和view.getFilePath()
一個實例是類的一個吸氣劑方法,該方法返回文件應保存的路徑(作爲字符串)。
getFilePath()看起來是這樣的:
public String getFilePath() {
return filePath;
}
而且我OceanLifeView這樣的:
OceanLifeView(String title, int type) {
if(...) {
...
}else if (title.equals("fileChooser")) {
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(FILES_ONLY);
if (type == 0) {
//Load Button functions
System.out.println("De-Serialisation started fileChooserGUI!");
returnVal = fileChooser.showOpenDialog(fileChooser);
} else {
//Save Button functions
System.out.println("Serialisation started fileChooserGUI!");
returnVal = fileChooser.showSaveDialog(fileChooser);
}
if (returnVal == JFileChooser.APPROVE_OPTION) {
filePath = fileChooser.getSelectedFile();
}
}
}
我會非常感謝任何人誰可以分享一些見解,因爲我遇到的問題或錯誤我實現了這個功能。
Does'view.getFilePath()'返回相同的'filePath'字符串在結尾分配的? – MNos
@MNos:是的,我在OceanLifeView類的OceanLifeView構造函數外部初始化filePath,以使用getter方法訪問它。 – Jub
您可以在'saveObjects'方法的第一行添加'System.out.println(「filePath:」+ filePath);'併爲我們提供輸出嗎? – MNos