编辑序列化文件

时间:2014-06-19 02:58:52

标签: java

我已经使用此代码在序列化文件上写入10个记录/对象,现在我想修改/编辑文件上写的第6个记录/对象,保持其他记录/对象相同。请告诉我怎么做?

import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.ObjectOutputStream;  
import java.io.Serializable;  
import java.util.Scanner;   

public class Write {     

    public static void main(String arg[]) throws FileNotFoundException, IOException {

        ObjectOutputStream to = new ObjectOutputStream(new FileOutputStream("file.cer"));
        Scanner out = new Scanner(System.in);
        String name;
        Double age;

        System.out.println("write NAME and AGE otherwise ctrl+z to teminate.");
        while(out.hasNext()) {
            name=out.nextLine();
            age=out.nextDouble();
            to.writeObject(new Data(name,age));
            System.out.println("write NAME and AGE otherwise ctrl+z to teminate.");
        }
        out.close();
        System.out.println("Ended");
    }
}

class Data implements Serializable {

    String name;
    Double age;

    public Data(String name, Double age) {
        this.name=name;
        this.age=age;
    }
}

2 个答案:

答案 0 :(得分:0)

我不认为可以编辑文件中的任何特定对象。你需要做的是,

  1. 从文件中读取所有数据。
  2. 编辑您想要的对象。
  3. 覆盖以前的数据。

答案 1 :(得分:0)

  

我想修改/编辑文件上写的第6个记录/对象,保持其他记录/对象相同。请告诉我该怎么做?

在实践中你不能。序列化流包含块标记和数据计数以及一般无法实现的各种事物。