1
我想序列化文件上的同一個對象,每次當我運行一個程序。這是一個簡單的算法來解釋我的問題。異常StreamCorruptedException:無效的類型代碼:AC
在begening我存儲String
在writer
。在最後我讀了一個文件。 這個程序的目標是如果我運行我的程序X時間,我存儲和我在屏幕X上打印我的對象。
class ReadFile {
static ObjectOutputStream writer = null;
public static void main(String[] args) throws IOException, ClassNotFoundException {
writer = new ObjectOutputStream(new FileOutputStream("trace", true));
store("String");
if (writer != null) {
writer.close();
}
open("file.tmp");
}
static public void store(String chaine) {
if (writer == null) {
return;
}
try {
writer.writeObject(chaine);
} catch (IOException ex) {
}
}
static public void open(String file) throws FileNotFoundException, IOException, ClassNotFoundException {
StringBuilder str = new StringBuilder();
ObjectInputStream objs;
try {
objs = new ObjectInputStream(new FileInputStream(file));
try {
while (true) {
Object obj = objs.readObject();
str.append(obj.toString());
}
} catch (EOFException ex) {
}
objs.close();
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
}
當我運行這個節目,我有這樣的錯誤:
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1355)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
at ReadFile.open(ReadFile.java:47)
at ReadFile.main(ReadFile.java:35)
我能做些什麼嗎?
您應該檢查它們,看看它們是否包含可能指出問題的任何有用信息,而不是捕捉異常並丟棄它們。另外,這是代碼的第35行? – DaveRlz
第35行是:'open(「file.tmp」);' – Mehdi
爲什麼不先將所有對象讀入列表中,然後添加要追加的對象,然後回寫到文件中。我知道這很耗時間,但是它對我來說很合適。看看這裏[鏈接](http://stackoverflow.com/questions/1194656/appending-to-an-objectoutputstream) – saikumarm