0
在打印文件的第一个记录之后发生此错误-java.io.StreamCorruptedException:无效的类型代码:AC 我正在写入对象到文件用下面的代码和读取所有的对象放入文件在Java中读取对象错误java.io.StreamCorruptedException:无效的类型代码:AC
演示代码
import java.io.*;
import java.util.*;
class Student implements Serializable
{
int no;
String nm;
void set(int no,String nm)
{
this.no=no;
this.nm=nm;
}
void get()
{
System.out.println(no+"--"+nm);
}
}
class write
{
public static void main(String[] args)
{
try
{
int no;
String s;
ObjectOutputStream oi=new ObjectOutputStream(new FileOutputStream("d:\\abc1.txt",true));
Scanner sc=new Scanner(System.in);
System.out.print("Enter Roll No:");
no=sc.nextInt();
System.out.print("Enter Name:");
sc.nextLine();
s=sc.nextLine();
Student s1=new Student();
s1.set(no,s);
oi.writeObject(s1);
oi.close();
Student sp;
ObjectInputStream ooi=new ObjectInputStream(new FileInputStream("d:\\abc1.txt"));
while((sp=(Student)ooi.readObject())!=null)
{
sp.get();
}
ooi.close();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
请帮我看所有的对象到文件中。
我认为你的问题是因为你在做sc.nextLine()两次。第二个我认为会在您按回车时创建的新行中读取。所以你需要删除上面的s = sc.nextLine()。 –