java-日常练习-序列化和反序列化

package a;
import org.apache.commons.lang.SerializationUtils;
import java.io.*;
public  class Hello implements Serializable {
    int id;
    String name;
    public void setId(int id){
        this.id=id;
    }
    public void  setName(String name){
        this.name=name;
    }
    @Override
    public String toString() {
        return "Hello{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
    public static void main(String[] args) throws IOException {
        Hello a=new Hello();
        a.setId(10);
        a.setName("王三");
        byte[] b = SerializationUtils.serialize(a);
        Hello c= (Hello) SerializationUtils.deserialize(b);
        FileOutputStream out= null;
        File file = new File("test.txt");
        if (null == file || 0 == file.length() || !file.exists()) {
            System.out.println("文件为空!");
        }
        try {
            out = new FileOutputStream(new File("test.txt").getAbsoluteFile());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        SerializationUtils.serialize(a,out);
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        File file2 = new File("test.txt");
        if (null == file2 || 0 == file2.length() || !file2.exists()) {
            System.out.println("文件为空!");
        }
        FileInputStream in= null;
        try {
            in = new FileInputStream(new File("test.txt").getAbsoluteFile());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Hello d=(Hello)SerializationUtils.deserialize(in);
        in.close();

        System.out.println(d);

    }
}

Hello{id=10, name=‘王三’}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值