![](/img/trans.png)
[英]What am I doing wrong when trying to create an object from an array using file input
[英]I'm trying to make a progrm that saves an object to a file and then reads the object from the file. What am I doing wrong?
我认为它会保存 object,因为它会生成 .txt 文件,但是当我运行程序时,在输入输入后它会输出“初始化流时出错”。 我是 Java 和一般编码的新手,所以我只是想知道我做错了什么。
这是我运行代码时得到的结果:
“你想要什么类型的服装?
大猩猩套装
你想要什么类型的面膜?
大猩猩”
这是你的衣服。
服装:大猩猩套装
面具:大猩猩
初始化流时出错”
我希望 object (“大猩猩套装”和“大猩猩”)的内容在最后一行到 output ,但它输出“错误初始化流”。
这是跑步者 class:
class RunHalloween2
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
Halloween outfit = new Halloween();
System.out.println("What type of costume do you want?");
outfit.setCostume(Input.nextLine());
System.out.println("What type of mask do you want?");
outfit.setMask(Input.nextLine());
System.out.println("");
System.out.println("This is your outfit.");
System.out.println("Costume: " + outfit.getCostume());
System.out.println("Mask: " + outfit.getMask());
try {
FileOutputStream f = new FileOutputStream(new File("myOutfit.txt"));
ObjectOutputStream o = new ObjectOutputStream(f);
// Write objects to file
o.writeObject(outfit);
o.close();
f.close();
FileInputStream fi = new FileInputStream(new File("myOutfit.txt"));
ObjectInputStream oi = new ObjectInputStream(fi);
// Read objects
outfit = (Halloween) oi.readObject();
System.out.println(outfit.toString());
oi.close();
fi.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
据我所知,可能有两个错误:-
1 - 您的文件名是myOutfit.txt
但它应该是myOutfit.ser
。
2 - 你的万圣节 class 没有实现序列化。
public class Halloween implements java.io.Serializable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.