This question already has an answer here:
StreamCorruptedException: invalid type code: AC
(1个答案)
2年前关闭。
打印文件-java.io.StreamCorruptedException的第一条记录后发生此错误:无效的类型代码:AC
我正在尝试使用以下代码将对象写入文件并将所有对象读取到文件中
演示代码
请帮助我将所有对象读入文件。
(1个答案)
2年前关闭。
打印文件-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);
}
}
}
请帮助我将所有对象读入文件。
最佳答案
Java序列化不支持“附加”。您不能将ObjectOutputStream写入文件,然后以附加模式再次打开文件并向其写入另一个ObjectOutputStream。您必须每次都重写整个文件。 (即,如果要将对象添加到文件中,则需要读取所有现有对象,然后使用所有旧对象和新对象再次写入文件)。