[英]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?
I think it saves the object because it makes the.txt file but when I run the program, after I input the inputs it outputs "Error initializing stream".我认为它会保存 object,因为它会生成 .txt 文件,但是当我运行程序时,在输入输入后它会输出“初始化流时出错”。 I am new to Java and coding in general so I was just wondering what I am doing wrong.
我是 Java 和一般编码的新手,所以我只是想知道我做错了什么。
Here i what I get when I run the code:这是我运行代码时得到的结果:
"What type of costume do you want? “你想要什么类型的服装?
gorilla suit大猩猩套装
What type of mask do you want?你想要什么类型的面膜?
gorilla "大猩猩”
This is your outfit.这是你的衣服。
Costume: gorilla suit服装:大猩猩套装
Mask: gorilla面具:大猩猩
Error initializing stream"初始化流时出错”
I would expect the contents of the object ("gorilla suit" and "gorilla") to output on the last line, but instead it outputs "Error initializing stream".我希望 object (“大猩猩套装”和“大猩猩”)的内容在最后一行到 output ,但它输出“错误初始化流”。
Here is the runner class:这是跑步者 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();
}
}
}
As per me There can be 2 mistake:-据我所知,可能有两个错误:-
1 - Your file name is myOutfit.txt
but it should be myOutfit.ser
. 1 - 您的文件名是
myOutfit.txt
但它应该是myOutfit.ser
。
2 - Your Halloween class does not implements serilization. 2 - 你的万圣节 class 没有实现序列化。
public class Halloween implements java.io.Serializable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.