我正在尝试执行一个程序,它可以读取我放入文件的所有对象。 输入效果很好,我放了8个对象,但是当我尝试从文件中读取它们时,它显示了java.io.StreamCorruptedException,它似乎无法显示我输入的所有方法。 我不知道自己哪里做错了。 有没有其他方法可以实现显示系统中每个对象的功能。 谢谢 我搜索解决方案 Appending to an ObjectOutputStream 但我无法理解答案,如果有人能解释,我将非常感激
import java.util.*;
import java.io.*;
public class driver
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
ObjectOutputStream objOut = null;
ObjectInputStream objIn = null;
Pet p = null;
Person owner = null;
do{
System.out.println("what u want to do");
System.out.println("1.add the pet\n2read the pet\n3get the weight\n4 system exit");
int option = keyboard.nextInt();
keyboard.nextLine();
switch(option)
{
case 1:
try
{
objOut = new ObjectOutputStream(new FileOutputStream("pet.dat",true));
owner = new Person();
owner.getInput();
System.out.println("Type of pet?(1-Mammal;2-Fish;3-Amphibian");
int type = keyboard.nextInt();
keyboard.nextLine();
switch (type)
{
case 1:
p = new Mammal();
p.owner = owner;
p.getInput();
objOut.writeObject(p);
objOut.close();
break;
case 2:
p = new Fish();
p.owner = owner;
p.getInput();
objOut.writeObject(p);
objOut.close();
break;
case 3:
p = new Amphibian();
p.owner = owner;
p.getInput();
objOut.writeObject(p);
objOut.close();
break;
}
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("here");
}
break;
case 2:
try
{
objIn = new ObjectInputStream(new FileInputStream("pet.dat"));
try
{
while(true)
{
p = (Pet)objIn.readObject();
System.out.println(p);
}
}
catch (EOFException e)
{
System.out.println("System ends");
}
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("something in driver");
}
break;
case 3:
try
{
objIn = new ObjectInputStream(new FileInputStream("pet.dat"));
try
{
while(true)
{
p = (Pet)objIn.readObject();
System.out.println(p.getname() + "'s weight is: " + p.getweight());
}
}
catch (EOFException e)
{
System.out.println("System ends");
}
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("something in driver");
}
break;
case 4:
System.exit(0);
}
}while(true);
}
}
答案 0 :(得分:0)
objOut = new ObjectOutputStream(new FileOutputStream("pet.dat",true));
您无法附加到对象流文件,至少在没有特殊措施的情况下。你得到了StreamCorruptedException:无效的类型代码AC',这确实是一个例外和错误,与你在评论中表达的明显信念相反。关于该主题的数百个问题重复。有关完整说明,请参阅here。