java - 我可以使用 FileChooser (javafx) 将序列化对象保存在文件中吗?

标签 java file serialization javafx save

标题很不言自明。我想保存连载的“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 实例上分别使用 showSaveDialogshowOpenDialog 来获取用于加载和保存的文件句柄对象。您可以在 FileInputStream 和 FileOutputStream 构造函数上使用此文件句柄对象。

关于java - 我可以使用 FileChooser (javafx) 将序列化对象保存在文件中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48264468/

相关文章:

java - Hadoop Writable和java.io.serialization有什么联系和区别?

java - 如何使用 spark-submit 将参数/属性传递给 Spark 作业

java - 使用 Gson lib 将 Json 转换为 Java 对象

file - 任何人都知道如何阅读像素翻译(pixtiff 压缩)?

cocoa - 返回标签上的文件名?

serialization - 使用 Doctrine MongoDB ODM 进行文档序列化

java - JPA映射2个实体表及其之间的关系表

java - 更改RecyclerView所有项目的View可见性

asp.net-mvc - 在mvc中拖放文件

c# - Unity 中的反序列化性能下降