[英]Saving an ArrayList to a file
I have a Arraylist, which i want to save in a file for use in the application another time, I've read several places that i can use this code to do this, but it doesn't work, it returns a error right after it prints out 3: 我有一个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");
}
and "kortene" is a ArrayList created like this: 而“ kortene”是这样创建的ArrayList:
public static ArrayList<Kort> kortene = new ArrayList<Kort>();
and Kort is a class i made, but that isn't relevant for this problem i assume.. Kort是我开设的一门课,但我认为与该问题无关。
the error i get is: java.io.NotSerializableException: java.awt.image.BufferedImage 我得到的错误是:java.io.NotSerializableException:java.awt.image.BufferedImage
but i dont have a BufferedImage, i just have a normal image in each of the classes... 但是我没有BufferedImage,每个类中只有一个普通图像...
Believe the compiler: if it says it's using BufferedImage
to hold your images in memory, then it's true. 相信编译器:如果它说它正在使用BufferedImage
将图像保存在内存中,那么它是正确的。 The javadocs say it's not Serializable
: javadocs说它不可Serializable
:
http://download.oracle.com/javase/1.5.0/docs/api/java/awt/image/BufferedImage.html http://download.oracle.com/javase/1.5.0/docs/api/java/awt/image/BufferedImage.html
You can mark your images as transient
and re-initialize them from the file system when you de-serialize later. 您可以将图像标记为transient
图像,并在以后反序列化时从文件系统重新初始化它们。 Give that a go. 放手
I assume the field declared in your class is of type Image
but it was assigned an object BufferedImage
during runtime. 我假设在您的类中声明的字段为Image
类型,但在运行时为它分配了一个对象BufferedImage
。 Thus it cannot write this to the output file since BufferedImage is not serializable. 因此,由于BufferedImage无法序列化,因此无法将其写入输出文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.