简体   繁体   中英

Size of object serialized

i want to calculate size of object p in this example and size of p serialized:

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 is :

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 is :

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

How about this? Just write into a ByteArrayOutputStream and see how big it gets...

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

Output

Bytes = 200

Try using the File.length() method to get the size of the file you wrote the object to.

If you want to know the size of the object in memory, try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM