我目前正在做一个项目,想保存一个对象到一个文件与ObjectOutputStream到一个位置,用户选择在JFileChooser的帮助下。但是对象总是保存在程序的根目录下,保存在名为"null“(%ProjectDirectory%/null)的文件中。
下面是我的方法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作为参数调用方法saveObject (filePath是一个字符串;我已经尝试使用文件)
saveObjects(view.getFilePath());view是OceanLifeView的实例,view.getFilePath()是该类的getter-method,它返回文件应保存到的路径(以字符串形式)。
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();
}
}
}我将非常感谢任何人,谁可以分享一些我遇到的问题或错误,我实现了这个功能的一些见解。
https://stackoverflow.com/questions/38168971
复制相似问题