1、ObjectInputStream() 的readObject()用于读入对象
ObjectOutputStream() 的writeObject()用于写入对象
那么请问怎么修改文件里的对象呢?
比如说文件“student.dat” 里有个对象stu;  我怎么能修改stu.name  的值呢?
2、加入student.dat 是个空文件
   FileInputStream file = new FileInputStream(student.dat);
   ObjectInputStream in = new ObjectInputStream(file);
   stu = in.readObject();会返回null还是怎样?  我运行了一下抛出IOException  了~
谢谢大虾们了~~~ 

解决方案 »

  1.   

    1,对象序列化后 好象是以什么字节码码 还是什么来着的保存的。 我们打开也看不懂 所以要修改只能重新序列化。
    2,   FileInputStream file = new FileInputStream("student.dat"); 
      

  2.   

    楼主的问题不是很清楚哦~
    空文件你为什么要读啊?读空文件返回IOException我感觉很正常哦……
      

  3.   

    1、序列化机制是为了自动补偿操作系统间的差异,利用它可以实现“有限持久化”。
    它保存的是一个对象整体,而且也有它自己的保存格式
    2、先判断file.available()是否等于0
      

  4.   


    import java.io.*;
    import java.util.*;class Data implements Serializable { // 实现序列话接口
    private int n; public Data(int n) {
    this.n = n;
    } public int getN() {
    return n;
    } public void setN(int n) {
    this.n = n;
    } public String toString() {
    return Integer.toString(n);
    }
    }class Worm implements Serializable {
    private static final long serialVersionUID = -935278024637286504L; public static void main(String[] args) throws ClassNotFoundException,
    IOException { // 序列话读入和写入Object可能会有这两个异常
    // 将你要序列化的object,保留到一个文件中
    Random rand = new Random();
    Data d = new Data(rand.nextInt(10)); // 构建你需要序列话的Object
    System.out.println("d   =   " + d);
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
    "c:\\worm.out")); // 准备写入的文件
    out.writeObject(d);
    out.flush();
    out.close(); // 执行到这里你可以看见worm.out这个文件,
    // 以下的代码读出你刚刚写入Object
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(
    "c:\\worm.out")); // 读你刚刚写入的文件
    Data d2 = (Data) in.readObject(); // 重新构建你刚刚写入的Object
    System.out.println("d2   =   " + d2);

    }
    }
      

  5.   

    怎么写回去?
    大侠能给个将DATA读出,改,然后写回的代码么?谢谢!!!!!
    我不懂的是,用ObjectInputStream只能读不能改的吧?而用ObjectOutputStream只能写不能读?
    那么怎么改啊~我对文件流还没完整弄明白!谢谢大侠指教!
      

  6.   

            ObjectInputStream in = new ObjectInputStream(new FileInputStream(
                    "c:\\worm.out")); // 读你刚刚写入的文件
             Data d2 = (Data) in.readObject(); // 重新构建你刚刚写入的Object这样不是读出一个对象了吗?
    然后对这个对象进行操作
    d2.××();
    这样不就能对 对象操作了吗
    然后把该对象写进去不就OK了吗
      

  7.   

    你的意思是 readObject()的时候是把d2“取”出来而不是“复制”出来对吗?
    我是怕按你的方法写回去的时候会不会文件里有2个d2了,一个修改前的一个修改后的。
    问个问题:
    如果文件“1.dat”里存了两个类d1,d2
    d3 = readObject();
    writeObject(d4);
    后“1.dat”里存的是d1,d4   还是d1,d2,d4  ???