本帖最后由 bird_not_fat 于 2013-10-14 11:38 编辑
- import java.io.Serializable;
- //这个类必须是实现了可序列化接口的
- public class Fruit implements Serializable{
- //自定义一个固定的序列化版本号
- public static final long serialVersionUID = 30L;
- private String apple;
- private String orange;
- private String watermelon;
- private static String banana;
- //constructor
- public Fruit(String apple,String orange,String watermelon,String banana){
- this.apple = apple;
- this.orange = orange;
- this.watermelon = watermelon;
- this.banana = banana;
- }
- public String getBanana() {
- return banana;
- }
- public void setBanana(String banana) {
- this.banana = banana;
- }
- //setter and getter
- public String getApple() {
- return apple;
- }
- public void setApple(String apple) {
- this.apple = apple;
- }
- public String getOrange() {
- return orange;
- }
- public void setOrange(String orange) {
- this.orange = orange;
- }
- public String getWatermelon() {
- return watermelon;
- }
- public void setWatermelon(String watermelon) {
- this.watermelon = watermelon;
- }
- }
复制代码 在这个类中我设置了一个静态属性banana,理论上静态存在于方法区内,序列化只能序列化堆内存中的对象,按理说banana是不能被序列化的。可是
下面代码:- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- /**
- * 示例:目的是对堆内存中的对象进行持久化存储
- * 因为是对对象进行操作,所以咱们采用对象流
- * 源和目标都是文件,所以对象流包装文件输入输出流
- * @author lt
- */
- public class ObjectStreamDemo {
- //序列化方法
- public static void toSerial(Object obj,File saveFile) throws FileNotFoundException,IOException{
- ObjectOutputStream oos = null;
- oos = new ObjectOutputStream(new FileOutputStream(saveFile));
- oos.writeObject(obj);
-
- }
- //反序列化方法
- public static Object fromSerial(File saveFile) throws FileNotFoundException,IOException, ClassNotFoundException{
- ObjectInputStream ois = null;
- ois = new ObjectInputStream(new FileInputStream(saveFile));
- Object getObj = ois.readObject();
- return getObj;
- }
- public static void main(String[] args) {
- Fruit fruit = new Fruit("苹果","橘子","西瓜","香蕉");
- File file = new File("d://serial.txt");
- if(file.exists()){
- try {
- // toSerial(fruit,file);
- Fruit getFruit = (Fruit)fromSerial(file);
- System.out.println(getFruit.getApple() + "---" +
- getFruit.getOrange() + "---" +
- getFruit.getWatermelon() + "---" +
- getFruit.getBanana());
- } catch (FileNotFoundException e) {
- System.out.println("无法再当前路径下创建文件!");
- } catch (IOException e) {
- System.out.println("对象流操作的文件不存在!");
- } catch (ClassNotFoundException e) {
- System.out.println("序列化文件未找到!");
- }
- }else{
- try {
- file.createNewFile();
- } catch (IOException e) {
- System.out.println("serial.txt创建失败!");
- }
- }
- }
- }
复制代码 运行结果: 苹果---橘子---西瓜---香蕉,香蕉也打印出来了,说明序列化成功了,这是为什么呢??
|