有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    I want to modify/edit only 6th record/object written on the file keeping other records/objects same. Please tell how I can do that?

    实际上,你不能。序列化流包含块标记和数据计数,以及使其在一般情况下不可能实现的所有内容

  2. # 2 楼答案

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

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