問題描述:
在向一個文件寫入可序列化對象時,每次只想向文件的末尾添加一個可序列化的對象,於是使用了FileOutputStream(文件名,true)間接的構建了ObjectOutputStream流對象,在向外讀數據的時候第一次運行的時候不會報錯,在第二次就會報java.io.StreamCorruptedException: invalid type code: AC錯誤。
原因:
在一個文件都有一個文件的頭部和文件體。由於對多次使用FileOutputStream(文件名,true)構建的ObjectOutputStream對象向同一個文件寫數據,在每次些數據的時候他都會向這個文件末尾先寫入header在寫入你要寫的對象數據,在讀取的時候遇到這個在文件體中的header就會報錯。導致讀出時,出現streamcorrput異常。
解決辦法:所以這里要判斷是不是第一次寫文件,若是則寫入頭部,否則不寫入。
代碼示例:
1.MyObjectOutputStream.java文件
1 import java.io.*;class MyObjectOutputStream extends ObjectOutputStream { 2 public MyObjectOutputStream() throws IOException { 3 super(); 4 } 5 public MyObjectOutputStream(OutputStream out) throws IOException { 6 super(out); 7 } 8 @Override
protected void writeStreamHeader() throws IOException { 9 return; 10 } 11 }
2.ObjectSave.Java文件
1 import java.io.*; 2 import java.util.*; 3 public class ObjectSave { 4 /** * @param args 5 * * @throws IOException 6 * * @throws IOException 7 * @throws FileNotFoundException 8 * */ 9 public static void main(String[] args) { 10 ObjectOutputStream out = null; 11 ObjectInputStream in = null; 12 List<User> list = new ArrayList<User>(); 13 list.add(new User("admin", "admin", "123", 1)); 14 list.add(new User("zhang", "zhang", "123", 0)); 15 String path = "d://abc"; 16 try { //判斷文件大小並調用不同的方法 17 File file = new File(path); 18 FileOutputStream fos = new FileOutputStream(file, true); 19 if(file.length()<1){ 20 out = new ObjectOutputStream(fos); 21 }else{ 22 out = new MyObjectOutputStream(fos); 23 } 24 //out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(path,true))); 25 //out.writeObject(Calendar.getInstance()); 26 //判斷文件大小並調用不同的方法 27 for (int i = 0; i < list.size(); i++) { 28 out.writeObject(list.get(i)); 29 } 30 } catch (Exception ex) { 31 ex.printStackTrace(); 32 } finally { 33 try { 34 out.close(); 35 } catch (IOException e) { 36 e.printStackTrace(); 37 } 38 } try { 39 in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(path))); 40 //Calendar date = (Calendar) in.readObject(); 41 //System.out.format("On %tA, %<tB %<te, %<tY:%n", date); 42 while (true) { 43 User user = (User) in.readObject(); 44 System.out.println(user.getName()); 45 } 46 } catch (EOFException e) { 47 48 } catch (Exception ex) { 49 ex.printStackTrace(); 50 } finally { 51 try { 52 in.close(); 53 } catch (IOException e) { 54 e.printStackTrace(); } 55 } 56 } 57 } 58 } 59 } 60 }