怎么建设境外网站,宜昌哪里有做网站的,个人主页英语,凡科建设网站.java.io.StreamCorruptedException: invalid type code: AC解决办法问题描述#xff1a; 在向一个文件写入可序列化对象时#xff0c;每次只想向文件的末尾添加一个可序列化的对象#xff0c;于是使用了FileOutputStream#xff08;文件名#xff0c;true#xff09;间接… .java.io.StreamCorruptedException: invalid type code: AC解决办法问题描述 在向一个文件写入可序列化对象时每次只想向文件的末尾添加一个可序列化的对象于是使用了FileOutputStream文件名true间接的构建了ObjectOutputStream流对象在向外读数据的时候第一次运行的时候不会报错在第二次就会报java.io.StreamCorruptedException: invalid type code: AC错误。 原因 在一个文件都有一个文件的头部和文件体。由于对多次使用FileOutputStream文件名true构建的ObjectOutputStream对象向同一个文件写数据在每次些数据的时候他都会向这个文件末尾先写入header在写入你要写的对象数据在读取的时候遇到这个在文件体中的header就会报错。导致读出时出现streamcorrput异常。 解决办法所以这里要判断是不是第一次写文件若是则写入头部否则不写入。 代码示例 1.MyObjectOutputStream.java文件 import java.io.*;class MyObjectOutputStream extends ObjectOutputStream {
public MyObjectOutputStream() throws IOException { super();
}public MyObjectOutputStream(OutputStream out) throws IOException {super(out);}
Override protected void writeStreamHeader() throws IOException { return;}
} 2.ObjectSave.Java文件 import java.io.*;
import java.util.*;
public class ObjectSave { /** * param args * * throws IOException * * throws IOException * throws FileNotFoundException * */ public static void main(String[] args) { ObjectOutputStream out null; ObjectInputStream in null;ListUser list new ArrayListUser();list.add(new User(admin, admin, 123, 1)); list.add(new User(zhang, zhang, 123, 0));String path d://abc; try { //判断文件大小并调用不同的方法 File file new File(path); FileOutputStream fos new FileOutputStream(file, true); if(file.length()1){ out new ObjectOutputStream(fos); }else{ out new MyObjectOutputStream(fos); } //out new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(path,true))); //out.writeObject(Calendar.getInstance()); //判断文件大小并调用不同的方法 for (int i 0; i list.size(); i) { out.writeObject(list.get(i)); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } try { in new ObjectInputStream(new BufferedInputStream(new FileInputStream(path)));//Calendar date (Calendar) in.readObject(); //System.out.format(On %tA, %tB %te, %tY:%n, date); while (true) { User user (User) in.readObject(); System.out.println(user.getName()); } } catch (EOFException e) { } catch (Exception ex) { ex.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } }} }}
}