【问题标题】:Saving an ArrayList to a file将 ArrayList 保存到文件
【发布时间】:2014-05-01 10:03:18
【问题描述】:

我有一个 Arraylist,我想将它保存在一个文件中以供下次在应用程序中使用,我已经阅读了几个可以使用此代码执行此操作的地方,但它不起作用,它返回一个打印出 3 后立即出错:

 private void savegame(){
    try {System.out.println("1");
        FileOutputStream preout = new FileOutputStream(new File("savedgame.ser"));
        System.out.println("2");
        ObjectOutputStream out = new ObjectOutputStream(preout);
        System.out.println("3");
        out.writeObject(kortene);
        System.out.println("4");
        out.close();
        System.out.println("5");
        preout.close();
        System.out.println("6");
        output = new FileWriter(new File("saved game settings.txt"));
        System.out.println("7");
        output.write(Indstillinger.BilledeMappe+"\n"+Indstillinger.AntalKort+
                "\n"+Indstillinger.AntalSpillere+"\n"+clicks+"\n"+Score);
        System.out.println("8");
        output.close();
        System.out.println("game save success");
    }catch (Exception e) {
        System.out.println("game save failed");
    }

而“kortene”是这样创建的 ArrayList:

public static ArrayList<Kort> kortene = new ArrayList<Kort>();

而 Kort 是我制作的一个类,但这与我假设的这个问题无关..

我得到的错误是:java.io.NotSerializableException: java.awt.image.BufferedImage

但我没有 BufferedImage,我只是在每个类中都有一个普通图像...

【问题讨论】:

    标签: java serialization


    【解决方案1】:

    相信编译器:如果它说它使用BufferedImage 将图像保存在内存中,那么它就是真的。 javadocs 说它不是Serializable

    http://download.oracle.com/javase/1.5.0/docs/api/java/awt/image/BufferedImage.html

    您可以将图像标记为transient,并在以后反序列化时从文件系统中重新初始化它们。试试看吧。

    【讨论】:

      【解决方案2】:

      我假设你的类中声明的字段类型为Image,但在运行时它被分配了一个对象BufferedImage。因此它无法将其写入输出文件,因为 BufferedImage 不可序列化。

      【讨论】:

        猜你喜欢
        • 2015-04-30
        • 2016-10-28
        • 2012-07-23
        • 1970-01-01
        • 1970-01-01
        • 2014-05-11
        • 2017-03-25
        • 2015-12-10
        • 2012-12-04
        相关资源
        最近更新 更多