我创建了一个简单的程序,将字符串输入从 cmd 序列化为 .ser 文件。部分要求是程序必须能够附加新输入并能够读取新输入和旧输入。但是我如果我在第二个输入之后阅读,则会得到 StreamCorruptedException ..
这是我在 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)
写文件.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();
}
}}
读取文件.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();
}
}}