【Java学习笔记】对象的流读写(串行化)

Serializable接口中没有任何的方法。当一个类声明要实现Serializable接口时,只是表明该类参加串行化协议,而不需要实现任何特殊的方法。

注意:Thread类不能被并行化

import java.io.Serializable; 
public class Goober implements Serializable { 
    private int width; 
    private String color; 
    private transient long work;//若你的类中有不能并行化的或者不想并行化的成员,则使用transient进行忽略 
    Goober() { 
        width = 99; 
        color = "puce"; 
    } 
    void setColor(String setting) { 
        color = setting; 
    } 
    String getColor() { 
        return(color); 
    } 
}

========写=======

import java.io.FileOutputStream; 
import java.io.ObjectOutputStream; 
import java.io.IOException; 
public class SerialDemo1 { 
    public static void main(String arg[]) { 
        Goober goober = new Goober(); 
        goober.setColor("magenta"); 
        try { 
            FileOutputStream fos = new FileOutputStream("sergoob"); 
            ObjectOutputStream oos = new ObjectOutputStream(fos); 
            oos.writeObject(goober); 
            oos.close(); 
        } catch(IOException e) { 
            System.out.println(e); 
        } 
    } 
}

========读=======

import java.io.FileInputStream; 
import java.io.ObjectInputStream; 
import java.io.IOException; 
public class SerialDemo2 { 
    public static void main(String arg[]) { 
        Goober goober = null; 
        try { 
            FileInputStream fis = new FileInputStream("sergoob"); 
            ObjectInputStream ois = new ObjectInputStream(fis); 
            goober = (Goober)ois.readObject(); 
            ois.close(); 
        } catch(IOException e) { 
            System.out.println(e); 
        } catch(ClassNotFoundException e) { 
            System.out.println(e); 
        } 
        String color = goober.getColor(); 
        System.out.println(color); 
    } 
}

注意:

1.Demo1和Demo2都要求有Goober这个类,也就是说,实质上,方法本身并没有因为串行化而保存在文件中。

2.真正的对象持久化建议使用关系型数据库或者XML文件,通用性较高,而串行化要求双方都是Java才可以。

 




本文转自gnuhpc博客园博客,原文链接:http://www.cnblogs.com/gnuhpc/archive/2012/12/17/2822321.html,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值