public static void main(String[] args) throws Exception {
                  //-----------------第一次写入数据----------------------
                  ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test2", true));
for (int i = 0; i < 5; i++) {
out.writeObject(new String(""+i));
}
out.flush();
out.close();
                  //-----------------第一次写入数据---------------------- out = new ObjectOutputStream(new FileOutputStream("test2", true));
out.writeObject(new String(""+10));  //这个数据没有输出
out.flush();
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("test2"));
while(true){
try{
System.out.println(in.readObject());
}catch(Exception e){
break;
}
}
}输出结果:0 1 2 3 4
问题:为什么只输出第一次写入的数据,第二次写入的数据没有输出,是不是写入对象流的文件不能被继续写入?

解决方案 »

  1.   

    你运行下面的程序,然后用UltraEdit打开这两个文件比较一下就会发现,在写入对象前,输出流还写了其他二进制值用于类型说明
    import java.io.*;
    public class Test{
    public static void main(String[] args) throws Exception {
    //-----------------第一次写入数据----------------------
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test2"));
    for (int i = 0; i < 5; i++) {
    out.writeObject(new String(""+i));
    }
    out.flush();
    out.close();
    //-----------------第一次写入数据----------------------

    out = new ObjectOutputStream(new FileOutputStream("test3"));
    out.writeObject(new String(""+0));  //这个数据没有输出
    out.flush();
    out.close();
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("test3"));

    }
    }
      

  2.   

    试验了一下,FileOutputStream当指定参数append为false时(所有用到的地方都写成false或者不写默认为false),连续的或者间断的多次写入文件都会覆盖原来的内容,当指定参数append为true时(全为true),第一次连续的多次写入文件有效不会覆盖,间断后写入的东西无效....
    不清楚这个类背后的原理,但是有其它类可以实现LZ的原始目的