2013-08-20 200 views
4

我创建了一个简单的程序,将字符串输入从cmd序列化为.ser文件。部分要求是程序必须能够追加新输入并能够读取新输入旧的输入..但我得到StreamCorruptedException如果我读后第二次输入..java序列化和反序列化

这里是我在CMD上运行..我该如何解决这个StreamCorruptedException,为什么会发生??。代码如下。

C:\Users\MSI\Desktop\Codes For Java>java WriteFile cc.ser 
Enter text and press ^Z or ^D to end. 
hah 
haha 
hahaha 
try 
^Z 

C:\Users\MSI\Desktop\Codes For Java>java WriteFile cc.ser 
Enter text and press ^Z or ^D to end. 
asd 
asd 
asd 
asd 
asd 
^Z 

C:\Users\MSI\Desktop\Codes For Java>java ReadFile cc.ser 
1: haha 
2: haha 
3: hahaha 
4: hahaha 
The Error is : 
java.io.StreamCorruptedException: invalid type code: AC 
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1375) 
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) 
    at ReadFile.main(ReadFile.java:23) 

WriteFile.java:

import java.io.*; 
public class WriteFile implements java.io.Serializable 
{ 
public static void main(String args[]) 
    { 
     try 
     { 
      File myFile = new File(args[0]); 

      BufferedReader br = new BufferedReader 
              (new InputStreamReader(System.in)); 
       ObjectOutputStream oos = new ObjectOutputStream 
              (new FileOutputStream(myFile,true)); 

      System.out.println("Enter text and press ^Z or ^D to end."); 

      String str; 

      while ((str = br.readLine()) != null) 

      { 

        oos.writeObject(str); 
      } 


      br.close(); 
      oos.close(); 
     } 

     catch (IOException i) 
     { 
      i.printStackTrace(); 
     } 
}} 

ReadFile.java:

import java.io.*; 
    public class ReadFile 
    {  
public static void main(String args[]) 
    { 

     try 
     { 
     int ctr = 0; 

     File myFile = new File(args[0]); 

      ObjectInputStream OIS = new ObjectInputStream 
               (new FileInputStream(myFile)); 
     String str; 



      while ((str = (String)OIS.readObject()) != null) 

      { 

       System.out.println(++ctr + ": " + str); 

      } 

      OIS.close();   
     } 

     catch (EOFException ex) 
     { 
      System.out.println("\nEnd of File Reached "); 
     } 



     catch (ClassNotFoundException c) 
     { 
      System.out.println("The Error is : "); 
      c.printStackTrace(); 
     }catch (IOException i) 
     { 
      System.out.println("The Error is : "); 
      i.printStackTrace(); 
     } 
    }} 
+0

[StreamCorruptedException:无效类型代码:AC]的可能重复(http://stackoverflow.com/问题/ 2393179/streamcorruptedexception-无效型码-AC)追加到一个ObjectOutputStream]的 –

+0

可能重复(http://stackoverflow.com/questions/1194656/appending-to-an-objectoutputstream) – SimonC

+0

'的readObject() '在流结束时不返回空值。你应该为这种情况捕捉'EOFException'。 – EJP

回答

1

每当你企图创建一个新的OutputStream对象为现有的输入流/努力,就会出现此异常甚至在写入内容之前读取,在这种情况下,从对象流读取的控制信息违反内部一致性检查。

在套接字的生命周期中使用单个OOS和OIS,并且不要在套接字上使用任何其他流。

另外你可能想在同一个程序中使用线程来实现相同的功能。

如果您想忘记所写的内容,请使用ObjectOutputStream.reset()。

-1

一些问题需要清晰,然后再进入代码并修复编码问题。

1)为什么你需要使用ObjectInputStream和ObjectOutputStream?如果你只是读写字符串,最好使用BufferedWriter和BufferedReader。我们只使用OIS和OOS来读写对象。

2)您的问题与序列化和反序列化无关。请做一个谷歌搜索,看看如何做正确的序列化和反序列化。在你的代码片段中:

public class WriteFile implements java.io.Serializable // there is no meaning to implement the mark up interface here. 

简而言之,只在POJO或数据对象上标记java.io.Serializable。

3)当你键入CTRL-C或CTRL-Z,有一个系统中断信号触发,整个系统将突然停止,这将导致数据写入的腐败。

我花了一点时间为您编写完整的工作示例。希望你能从我的样本中获得某些东西。

ConsoleWriter

/** 
    * Write Console String to a file 
    * When you type quit or save it will write to the file in one go. 
    * 
    * @author Seabook Chen 
    * 
*/ 
public class SimpleConsoleWriter { 
    private static final String NEW_LINE = System.getProperty("line.separator"); 

    public static void main(String[] args) { 

     if (args == null || args.length == 0) { 
      throw new RuntimeException("Please specify the file name!!!"); 
     } 

     String filepath = args[0]; 

     Scanner in = new Scanner(System.in); 
     System.out.println("Please input your comments ...."); 
     System.out.println("Type quit to finish the input! Please type exact quit to quit!!!"); 
     System.out.println("Type save to write to the file you specified. "); 

     StringBuilder sb = new StringBuilder(); 
     while(true) { 
      String input = in.nextLine(); 

      if ("quit".equalsIgnoreCase(input) || "save".equalsIgnoreCase(input)) { 
       System.out.println("Thanks for using the program!!!"); 
       System.out.println("Your input is stored in " + filepath); 
       break; 
      } 

      sb.append(input); 
      sb.append(NEW_LINE); 

     } 

     FileWriter fw = null; 
     BufferedWriter bw = null; 

     try { 
      fw = new FileWriter(filepath, true); 
      bw = new BufferedWriter(fw); 
      bw.write(sb.toString(), 0, sb.toString().length()); 
      bw.flush(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (fw != null) { 
       try { 
        fw.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 

      if (bw != null) { 
       try { 
        bw.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 


    } 
} 

SimpleConsoleReader

/** 
* Read a file and output in the console 
* 
* @author Seabook Chen 
* 
*/ 
public class SimpleConsoleReader { 
    public static void main(String[] args) { 
     if (args == null || args.length == 0) { 
      throw new RuntimeException("Please specify the file name!!!"); 
     } 
     File file = new File(args[0]); 
     FileReader fr = null; 
     BufferedReader br = null; 
     String nextLine = null; 
     try { 
      fr = new FileReader(file); 
      br = new BufferedReader(fr); 

      while((nextLine = br.readLine()) != null) { 
       System.out.println(nextLine); 
      } 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (fr != null) { 
       try { 
        fr.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 

      if (br != null) { 
       try { 
        br.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 
} 
+0

“您的问题与序列化无关”错误。您的'ConsoleWriter'示例没有检查'readLine()'结果为null,因此会抛出'NullPointerExceptions'。答案大多不相关。 -1 – EJP

+0

我不知道你为什么给我投票?我花了30分钟来编写程序来帮助回答问题,没有人表示赞赏。代码中可能存在错误。这只是一个快速演示。无论如何,让它成为。 – Seabook

+0

我再次检查了我的代码。没有NPE,所以你永远不会运行我的代码,只是猜测。无论如何,我没有太多的话要说。 – Seabook

0

我觉得出现这个问题,因为你企图被写入甚至前必读。

0

我编辑我的代码从上面

public class AppendingObjectOutputStream extends ObjectOutputStream { 

public AppendingObjectOutputStream(OutputStream out) { 
    super(out); 
} 

@Override 
protected void writeStreamHeader() throws IOException { 
    // do not write a header, but reset: 
    // this line added after another question 
    // showed a problem with the original 
reset(); 
}} 

更好地完善这个代码的任何建议中提到的问题,阅读一些这个问题的答案Appending to an ObjectOutputStream

import java.io.*; 



public class WriteFile 
implements java.io.Serializable 
{ 

public static void main(String args[]) 
    { 

     try 
     { 
      File myFile = new File(args[0]); 

      BufferedReader br = 
          new BufferedReader(new InputStreamReader(System.in)); 

      if (myFile.exists()) 
       { 
        AppendingObjectOutputStream AOOS = new AppendingObjectOutputStream(new FileOutputStream(myFile,true));          
         System.out.println("Enter text and press ^Z or ^D to end."); 

        String str; 

          while ((str = br.readLine()) != null) 

         { 

          AOOS.writeObject(str); 
         } 


        br.close(); 
        AOOS.flush(); 

       } 

     else 
      { 
      ObjectOutputStream OOS = new ObjectOutputStream(new FileOutputStream(myFile,true)); 
      System.out.println("Enter text and press ^Z or ^D to end."); 

      String str; 

      while ((str = br.readLine()) != null) 

      { 

        OOS.writeObject(str); 
      } 


      br.close(); 
      OOS.flush(); 
      } 

     } 
     catch (IOException i) 
     { 
      i.printStackTrace(); 
     } 

}} 

,并添加新的下课?对不起只是一个新手Java编程

这里是我在CMD

的Microsoft Windows新的运行[版本6.1.7601] 版权所有(C)2009年微软公司。版权所有。

C:\ Users \ MSI> cmd 'cmd'不被识别为内部或外部命令, 可操作的程序或批处理文件。

C:\Users\MSI\Desktop\Codes For Java>java WriteFile haha.ser 
Enter text and press ^Z or ^D to end. 
a 
b 
c 
d 
^Z 

C:\Users\MSI\Desktop\Codes For Java>java WriteFile haha.ser 
Enter text and press ^Z or ^D to end. 
e 
f 
g 
^Z 

C:\Users\MSI\Desktop\Codes For Java>java ReadFile haha.ser 
1: a 
2: b 
3: c 
4: d 
5: e 
6: f 
7: g 

End of File Reached 

我did'nt改变我readfile.java文件...感谢您的答案= d