gpt4 book ai didi

java - 序列化对象的大小

转载 作者:行者123 更新时间:2023-12-01 19:06:42 25 4
gpt4 key购买 nike

我想计算本例中对象 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)人员是:

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";
}
}

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();
}
}
}
}

最佳答案

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

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

输出

Bytes = 200

关于java - 序列化对象的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9791245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com