介绍:
ObjectOutputStream流是一个字节流,所以它是基于字节的。构造方法里面需要传入一个OutputStream对象。
ObjectOutputStream流和DataOutputStream流一样,写入文件的数据会出现乱码的情况。
需要实例化的类一定要实现Serializable接口。
代码样例:
ObjectOutputStream o=new ObjectOutputStream(new FileOutputStream("filename"));
o.writeObject(list);
o.close();
ObjectInputStream oi=new ObjectInputStream(new FileInputStream("filename"));
ArrayList<Account>list=new ArrayList<>();
list=(ArrayList<Account>)oi.readObject();
list.add(account);
oi.close();
一般的,通过ObjectOutputStream只在文件中输出一个对象类, 如果要多次输出多个类则会在文件中则每个类之间会自动通过StreamHeader输出4个字节,导致在进行类的读取是出现报错 注 StreamHeader: protected void writeStreamHeader() throws IOException { bout.writeShort(STREAM_MAGIC); bout.writeShort(STREAM_VERSION); }//一个short 2个字节,两个都是short类型,占4个字节。 改进办法: 方法一: 我们只要不写入StreamHeader不就可以了,这样分别继承ObjectOutputStream和ObjectInputStream, 分别重写writeStreamHeader和readStreamHeader方法,让他们doNothing就Okay了。
public class MyObjectOutputStream extends ObjectOutputStream {
public MyObjectOutputStream(OutputStream os) throws IOException, SecurityException {
super(os);
}
@Override
protected void writeStreamHeader() throws IOException {
super.reset();
}
}
public class MyObjectInputStream extends ObjectInputStream{
public MyObjectInputStream(InputStream in) throws IOException {
super(in);
}
@Override
protected void readStreamHeader() throws IOException, StreamCorruptedException {
}
}
方法二: 或者 我们在每次从文件中读取类时 通过 byte[4] 每次将这四个字节读出后 再读入到类中 方法三(最为实用): 我们直接将要输入到文件中的所有类储存到List集合中,只在文件中输入一个List类, 而在我每从文件中读类时,也只从文件中读出一个类赋值给List集合,接下来的具体操作只对List集合进行。 代码样例:
ObjectInputStream oi=new ObjectInputStream(new FileInputStream("filename"));
ArrayList<Account>list=new ArrayList<>();
list=(ArrayList<Account>)oi.readObject();
list.add(account);
ObjectOutputStream o=new ObjectOutputStream(new FileOutputStream("filename"));
o.writeObject(list);
o.flush();
oi.close();