Java-序列化对象到Gzip文件中

Java-序列化对象到Gzip文件中

Tags: Java

摘要

Java-序列化对象到Gzip文件中

序列化对象到Gzip文件

之前的例子中有介绍序列化对象到普通文件中,这里是要序列化到Gzip文件中,只需要在FileOutputStream的基础上再包裹一层GZIPOutputStream.

序列化对象到Gzip文件例子

要被序列化的Bean对象

package cn.javacore.io.serialization;

import java.io.Serializable;

public class Address implements Serializable {

    String street;
    String country;

    public void setStreet(String street) {
        this.street = street;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getStreet() {
        return this.street;
    }

    public String getCountry() {
        return this.country;
    }

    @Override
    public String toString() {
        return new StringBuffer(" Street : ")
                .append(this.street)
                .append(" Country : ")
                .append(this.country).toString();
    }

}

序列化代码

package cn.javacore.io.zip;

import cn.javacore.io.serialization.Address;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.zip.GZIPOutputStream;

public class _06_Serializer2Gzip implements Serializable {

    public static void main(String args[]) {

        _06_Serializer2Gzip serializer = new _06_Serializer2Gzip();
        serializer.serializeAddress("信息路", "中国北京");
    }

    public void serializeAddress(String street, String country) {

        Address address = new Address();
        address.setStreet(street);
        address.setCountry(country);

        try {

            FileOutputStream fos = new FileOutputStream("/home/zhu/javacore.cn/address.gz");
            GZIPOutputStream gz = new GZIPOutputStream(fos);

            ObjectOutputStream oos = new ObjectOutputStream(gz);

            oos.writeObject(address);
            oos.close();

            System.out.println("Done");

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}