标题很不言自明。我想保存连载的“spiel” 使用文件选择器作为“name.ser”文件。我还想加载该文件并将其返回到我的 Controller 。我不知道如何连接 objectoutputstream 和文件选择器。
public class Speicher {
public void spielstandSpeichern(Spiel spiel, String name) { // Save File
try{
FileChooser fs = new FileChooser();
fs.setInitialDirectory(new File("/Saves"));
fs.setTitle("Spiel speichern");
fs.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("Ser", ".ser")
);
//File file =
FileOutputStream fos = new FileOutputStream("Saves/save1.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(spiel);
oos.close();
fos.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
public Spiel spielstandLaden() { // Load File
Spiel spiel = null;
try{
FileInputStream fis = new FileInputStream("Saves/save1.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
spiel = (Spiel) ois.readObject();
ois.close();
fis.close();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
return spiel;
}
}
提前致谢:)
最佳答案
您可以在 FileChooser 实例上分别使用 showSaveDialog
和 showOpenDialog
来获取用于加载和保存的文件句柄对象。您可以在 FileInputStream 和 FileOutputStream 构造函数上使用此文件句柄对象。
关于java - 我可以使用 FileChooser (javafx) 将序列化对象保存在文件中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48264468/