对象大小序列化

时间:2012-03-20 16:49:01

标签: java

我想计算此示例中对象p的大小和p序列化的大小:

public class Main {

    static public void main(String[] args) throws IOException {
        Personne p1 = new Personne("name1", "username1", 25);
        SrzDrz sr = new SrzDrz(p1, "file1");

        // Calculate size of(sr) and p1 ???
    }
}

Class Personne是:

public class Personne implements Serializable {

    static private final long serialVersionUID = 6L;
    private String nom;
    private String prenom;
    private Integer age;

    public Personne(String nom, String prenom, Integer age) {
        this.nom = nom;
        this.prenom = prenom;
        this.age = age;
    }

    public String toString() {
        return nom + " " + prenom + " " + age + " years";
    }
}

Class SrzDrz是:

public class SrzDrz {

    SrzDrz(Personne p, String name) throws IOException {

        FileOutputStream fos = new FileOutputStream(name);
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        try {
            oos.writeObject(p);
            oos.flush();
            System.out.println(p + " serialized");
        } finally {
            try {
                oos.close();
            } finally {
                fos.close();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:4)

这个怎么样?只需写入ByteArrayOutputStream,看看它有多大......

ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(byteOutput);
stream.writeObject(p1);
stream.close();
System.out.println("Bytes = " + byteOutput.toByteArray().length);

输出

Bytes = 200

答案 1 :(得分:0)

尝试使用File.length()方法获取您编写对象的文件的大小。

如果你想知道内存中对象的大小,试试这个:

http://www.javamex.com/classmexer/