将ArrayList保存到文件

时间:2011-04-24 11:16:29

标签: java serialization

我有一个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,我只是在每个类中都有一个正常的图像......

2 个答案:

答案 0 :(得分:5)

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

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

您可以将图像标记为transient,并在稍后反序列化时从文件系统重新初始化它们。放手一搏。

答案 1 :(得分:2)

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