2013-10-22 27 views
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); 
     } 
    } 
} 

请帮我看所有的对象到文件中。

+0

我认为你的问题是因为你在做sc.nextLine()两次。第二个我认为会在您按回车时创建的新行中读取。所以你需要删除上面的s = sc.nextLine()。 –

回答

3

Java序列化不支持“附加”。您无法将ObjectOutputStream写入文件,然后再以附加模式打开文件,并向其写入另一个ObjectOutputStream。你必须重新编写整个文件每次。 (即,如果要将对象添加到文件中,则需要读取所有现有对象,然后再次使用所有旧对象和新对象编写该文件)。

相关问题