A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 古银平 中级黑马   /  2012-11-5 09:56  /  2936 人查看  /  12 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

编程实现对象的序列化和反序列化。(写出自己的思路,一定要有注释,必须是以自己理解写出来的)

评分

参与人数 1技术分 +1 收起 理由
滔哥 + 1

查看全部评分

12 个回复

倒序浏览
赞一个!{:soso_e179:}
回复 使用道具 举报
暂时还没学到这……先围观一下……
回复 使用道具 举报
先占个楼     
回复 使用道具 举报
  1. package com.snow;

  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedOutputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.ObjectInputStream;
  8. import java.io.ObjectOutputStream;

  9. /**
  10. * 重点:
  11. * 序列化:将对象转成二进制流 存存入到磁盘、数据库等
  12. * 1)对象(引用类型):内容+类型
  13. * 2)不是所有的对象都可以序列化,需要序列化的对象必须有标识
  14. * :可序列标识 空接口(Serializable)
  15. * 反序列化:将对象的二进制流还原成对象 前提:(已经序列化)
  16. * @author Administrator
  17. *
  18. */
  19. public class ObjectOutputStreamDemo01 {
  20.         public static void main(String[] args) {
  21.                 Student stu=new Student();
  22.                 stu.setAge(20);
  23.                 stu.setGender(true);
  24.                 stu.setName("打不死的小强");
  25.                 ser(stu);               
  26.                 Student stu1=(Student)deSer();
  27.                 System.out.println(stu1.getAge());
  28.         }
  29.         /**
  30.          * 序列化 对象保存到硬盘
  31.          *
  32.          * @param obj
  33.          */
  34.         public static void ser(Object obj){
  35.        
  36.                
  37.                 ObjectOutputStream oos=null;
  38.                
  39.                 try {
  40.                         oos = new ObjectOutputStream(new BufferedOutputStream(
  41.                                         new FileOutputStream(new File("C:/ser.txt"))));
  42.                         oos.writeObject(obj);                       
  43.                 } catch (Exception e) {
  44.                 }finally{
  45.                         try {
  46.                                 if (null != oos) {
  47.                                         oos.close();
  48.                                 }
  49.                         } catch (Exception e2) {
  50.                         }
  51.                 }
  52.         }
  53.        
  54.         /**
  55.          * 反序列化:前提必须序列化
  56.          */
  57.         public static Object deSer(){
  58.                 ObjectInputStream ois=null;
  59.                
  60.                 try {
  61.                         ois = new ObjectInputStream(new BufferedInputStream(
  62.                                         new FileInputStream(new File("C:/ser.txt"))));
  63.                        
  64.                         return ois.readObject();
  65.                        
  66.                        
  67.                 } catch (Exception e) {
  68.                 }finally{
  69.                         try {
  70.                                 if (null != ois) {
  71.                                         ois.close();
  72.                                 }
  73.                         } catch (Exception e2) {
  74.                         }
  75.                 }
  76.         return null;
  77.         }
  78.        
  79.        
  80. }
复制代码
  1. package com.snow;

  2. import java.io.Serializable;
  3. /**
  4. * 默认属性都是可序列化
  5. * 如果部分属性不需要序列化: transient
  6. * @author Administrator
  7. *
  8. */
  9. public class Student implements Serializable{
  10.         private String name;
  11.         //此属性不被序列
  12.         private transient int age;
  13.         private transient boolean gender;
  14.                
  15.         public Student() {
  16.                 super();
  17.                 // TODO Auto-generated constructor stub
  18.         }
  19.         public Student(String name, int age, boolean gender) {
  20.                 super();
  21.                 this.name = name;
  22.                 this.age = age;
  23.                 this.gender = gender;
  24.         }
  25.         public String getName() {
  26.                 return name;
  27.         }
  28.         public void setName(String name) {
  29.                 this.name = name;
  30.         }
  31.         public int getAge() {
  32.                 return age;
  33.         }
  34.         public void setAge(int age) {
  35.                 this.age = age;
  36.         }
  37.         public boolean isGender() {
  38.                 return gender;
  39.         }
  40.         public void setGender(boolean gender) {
  41.                 this.gender = gender;
  42.         }
  43.        
  44.        
  45.        
  46.                
  47. }
复制代码

点评

记得实现equals和hashCode方法  发表于 2012-11-5 11:51

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 赞一个!

查看全部评分

回复 使用道具 举报
本帖最后由 罗宝 于 2012-11-5 10:39 编辑

试一下!
  1. /**
  2. * 功能:编程实现对象的序列化和反序列化
  3. */
  4. package com.test1;

  5. import java.io.*;
  6. import java.util.Date;

  7. public class Test {


  8. public static void main(String[] args) throws Exception {
  9.         
  10.         //创建一个文件输入流对象
  11.         FileOutputStream fos=new FileOutputStream("d:\\objFile.obj");

  12.         ObjectOutputStream oos = new ObjectOutputStream(fos);

  13.         //序列化对象

  14.         Customer customer = new Customer("小红", 22);

  15.         oos.writeObject("HelloWorld!");

  16.         oos.writeObject(new Date());

  17.         oos.writeObject(customer);

  18.         //写入基本类型数据
  19.         oos.writeInt(12345);
  20.         
  21.         //关闭流
  22.         oos.close();

  23.         //反序列化对象

  24.         FileInputStream fis=new FileInputStream("d:\\objFile.obj");
  25.         ObjectInputStream ois = new ObjectInputStream(fis);

  26.         System.out.println("obj1:" + (String) ois.readObject());

  27.         System.out.println("obj2:" + (Date) ois.readObject());

  28.         Customer obj3 = (Customer) ois.readObject();

  29.         System.out.println("obj3:" + obj3);

  30.         int obj4 = ois.readInt();

  31.         System.out.println("obj4:" + obj4);

  32.         ois.close();

  33.         }

  34. }

  35. class Customer implements Serializable {

  36.         private String name;

  37.         private int age;

  38.         //构造方法,封装私有成员
  39.         public Customer(String name, int age) {

  40.                 this.name = name;

  41.                 this.age = age;

  42.         }

  43. public String toString() {

  44.         return "名字是:" + name + ", 年龄是:" + age;

  45.         }

  46. }

复制代码

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 神马都是浮云

查看全部评分

回复 使用道具 举报
  1. import java.io.FileInputStream;
  2. import java.io.FileOutputStream;
  3. import java.io.IOException;
  4. import java.io.ObjectInputStream;
  5. import java.io.ObjectOutputStream;
  6. import java.io.Serializable;
  7. import org.junit.Test;

  8. public class Demo {

  9.         // 序列化对象
  10.         @Test
  11.         public void write() throws IOException {
  12.                 // 先创建一个student类
  13.                 Student stu = new Student("xiaohuihui", 1);

  14.                 ObjectOutputStream out = null;
  15.                 //ObjectOutputStream 将 Java 对象的基本数据类型和图形写入 OutputStream。
  16.                 //可以使用 ObjectInputStream 读取(重构)对象。通过在流中使用文件可以实现对象的持久存储
  17.                 try {
  18.                         out = new ObjectOutputStream(new FileOutputStream(
  19.                                         "testfile/test.txt"));
  20.                         out.writeObject(stu);//writeObject 方法用于将对象写入流中
  21.                 } finally {
  22.                         if (out != null) {
  23.                                 out.close();
  24.                         }
  25.                 }

  26.         }

  27.         // 反序列化对象
  28.         @Test
  29.         public void read() throws IOException, ClassNotFoundException {

  30.                 Student stu = null;
  31.                 ObjectInputStream in = null;
  32.                 //ObjectInputStream 对以前使用 ObjectOutputStream 写入的基本数据和对象进行反序列化。
  33.                 try {
  34.                         in = new ObjectInputStream(new FileInputStream("testfile/test.txt"));
  35.                         stu = (Student) in.readObject();
  36.                 } finally {
  37.                         if (in != null) {
  38.                                 in.close();
  39.                         }
  40.                 }
  41.                 System.out.println(stu.getName()+"  "+stu.getAge());

  42.         }

  43. }

  44. // studnent 类
  45. /*
  46. * 类通过实现 java.io.Serializable 接口以启用其序列化功能。
  47. * 未实现此接口的类将无法使其任何状态序列化或反序列化。
  48. */
  49. class Student implements Serializable {
  50.         private String name;
  51.         private int age;

  52.         public Student() {
  53.         }

  54.         public Student(String name, int age) {
  55.                 this.name = name;
  56.                 this.age = age;
  57.         }

  58.         public String getName() {
  59.                 return name;
  60.         }

  61.         public void setName(String name) {
  62.                 this.name = name;
  63.         }

  64.         public int getAge() {
  65.                 return age;
  66.         }

  67.         public void setAge(int age) {
  68.                 this.age = age;
  69.         }

  70. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 赞一个!

查看全部评分

回复 使用道具 举报
  1. package cn.itcast.heima2;

  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.ObjectInputStream;
  6. import java.io.ObjectOutputStream;
  7. import java.io.Serializable;

  8. public class Test {

  9.         /**
  10.          * @param args
  11.          * @throws Exception
  12.          */
  13.         public static void main(String[] args) throws Exception {
  14.                 //创建Person对象
  15.                 Person p = new Person("zhangsan", 15);

  16.                 //序列化,将对象保存到硬盘上
  17.                 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("c:\\1.txt")));
  18.                 oos.writeObject(p);
  19.                 oos.close();
  20.                
  21.                 //清空对象
  22.                 p = null;

  23.                 //反序列化,将对象从硬盘上读出并打印
  24.                 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c:\\1.txt"));
  25.                 p = (Person)ois.readObject();
  26.                 p.getPerson();
  27.         }

  28. }

  29. //Person类实现Serializable接口,从而可以被序列化和反序列化
  30. class Person implements Serializable{
  31.         public String name;
  32.         int age;
  33.         public Person(String name, int age){
  34.                 this.name = name;
  35.                 this.age = age;
  36.         }
  37.        
  38.         public void getPerson(){
  39.                 System.out.println("name: " + name);
  40.                 System.out.println("age: " + age);
  41.         }
  42. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 代码封装性

查看全部评分

回复 使用道具 举报
本帖最后由 朱宏青 于 2012-11-5 21:11 编辑

占楼 晚上贴程序.

搞定。我写的是单独一个类,功能需要调用才能实现。

利用了单例模式来使程序安全运行 并且插入了视图方便使用。

具体代码如下:
  1. import java.io.*;
  2. import java.util.*;
  3. import javax.swing.*;
  4. //创建一个序列化的功能类    利用单例模式实现序列化以及反序列化.
  5. class SerIO {
  6.         private static SerIO serio = null;
  7.         private SerIO() {

  8.         }

  9.         public static SerIO getSerio() {
  10.                 if (serio == null) {
  11.                         serio = new SerIO();
  12.                 }
  13.                 return serio;
  14.         }
  15. //需要一个object作为参数录入 然后实现该object的序列化
  16.         private void setSer(Object ob) throws IOException {
  17.                 Scanner input = new Scanner(System.in);
  18.                 System.out.println("请输入存储序列化的文本名称:(注意不要与现有文件重名)");
  19.                 FileOutputStream fos = new FileOutputStream(input.nextLine());
  20.                 ObjectOutputStream oos = new ObjectOutputStream(fos);
  21.                 oos.writeObject(ob);
  22.                 oos.flush();
  23.         }
  24. //获取需要的文件实现反序列化
  25.         private Object getSer() throws ClassNotFoundException,IOException{
  26.                 //利用swing组建来扩展,使用户视图化操作
  27.                 JFileChooser jc = new JFileChooser();
  28.                 jc.showDialog(null,"请选择需要反序列化的文件:(不要乱选哦~)");
  29.                 File file = jc.getSelectedFile();
  30.         String str = file.getName();
  31.         String stemp = str.substring(str.lastIndexOf("."));
  32.         //判断后缀名是否规范
  33.         if(stemp.toLowerCase().equals(".txt")){
  34.                 //实现反序列化
  35.                 stemp = str.substring(0,str.lastIndexOf("."));
  36.                 FileInputStream fis = new FileInputStream(stemp);
  37.                 ObjectInputStream ois = new ObjectInputStream(fis);
  38.                 Object ob = ois.readObject();
  39.                 return ob;
  40.         }else{
  41.         System.out.println("反序列化失败!(请好好选择文件 谢谢合作!)");
  42.         return null;
  43.         }
  44.         }
  45. }
复制代码
绝对给力有木有!

求分~

评分

参与人数 1技术分 +1 收起 理由
冯海霞 + 1 赞一个!

查看全部评分

回复 使用道具 举报
对象序列化包括如下步骤:

1) 创建一个对象输出流,它可以包装一个其他类型的目标输出流,如文件输出流;

2) 通过对象输出流的writeObject()方法写对象。

对象反序列化的步骤如下:

1) 创建一个对象输入流,它可以包装一个其他类型的源输入流,如文件输入流;

2) 通过对象输入流的readObject()方法读取对象。

下面让我们来看一个对应的例子,类的内容如下:

import java.io.*;

import java.util.Date;


public class Object{

       public static void main(String[] args) throws Exception {

              ObjectOutputStream out = new ObjectOutputStream

                     (new FileOutputStream("D:""objectFile.obj"));

              //序列化对象

              Customer customer = new Customer("李冰",1);

              out.writeObject("你好!");

              out.writeObject(new Date());

              out.writeObject(customer);

              out.writeInt(123); //写入基本类型数据

              out.close();

              //反序列化对象

              ObjectInputStream in = new ObjectInputStream

                     (new FileInputStream("D:""objectFile.obj"));

              System.out.println("obj1=" + (String) in.readObject());

              System.out.println("obj2=" + (Date) in.readObject());

              Customer obj3 = (Customer) in.readObject();

              System.out.println("obj3=" + obj3);

              int obj4 = in.readInt();

              System.out.println("obj4=" + obj4);

              in.close();

       }

}

class Customer implements Serializable {

       private String name;

       private int age;

       public Customer(String name, int age) {

              this.name = name;

              this.age = age;

       }

       public String toString() {

              return "name=" + name + ", age=" + age;

       }

}

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 赞一个!

查看全部评分

回复 使用道具 举报
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;
import java.io.Serializable;



public class SerializableDemo {

        /**
         * 对象的序列化:就是指将对象从内存中存入到磁盘、数据库中等等
         * 对象的反序列化:就是将对象从磁盘、数据库读到内存中
         * @param args
         */
        public static void main(String[] args) {
                SerializableAttachment attachment = new SerializableAttachment("hello", 100);
                SerializableDemo sd = new SerializableDemo();
                sd.store(attachment, "F:\\1.txt");
                SerializableAttachment sa = (SerializableAttachment) sd.getObject("F:\\1.txt");
                System.out.println(sa);
        }


       
        //对象的序列化,存入磁盘的类必须实现了Serializable接口
        public void store(Object obj, String path){
                if (!(obj instanceof Serializable)) {
                        System.out.println(obj.getClass().getName() + " 这个类没有实现Serializable,不能被序列化");
                        return;
                }
                ObjectOutputStream oos = null;
                try {
                        oos = new ObjectOutputStream(new FileOutputStream(path));
                        oos.writeObject(obj);
                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                } finally{
                        if (null != oos) {
                                try {
                                        oos.close();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                }
        }
       
       
        //对象的反序列化
        public Object getObject(String path){
                File src = new File(path);
                Object obj = null;
                if (!src.exists()) {
                        System.out.println(path + "不存在!");
                }else {
                        ObjectInputStream ois = null;
                       
                        try {
                                ois = new ObjectInputStream(new FileInputStream(src));
                                obj = ois.readObject();
                        } catch (FileNotFoundException e) {
                                e.printStackTrace();
                        } catch (IOException e) {
                                e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                        }finally{
                                if (null != ois) {
                                        try {
                                                ois.close();
                                        } catch (IOException e) {
                                                e.printStackTrace();
                                        }
                                }
                        }
                }
                return obj;
        }
       
}

class SerializableAttachment implements Serializable{
        private String name;
        private int age;

        public String getName() {
                return name;
        }
        public void setName(String name) {
                this.name = name;
        }
        public int getAge() {
                return age;
        }
        public void setAge(int age) {
                this.age = age;
        }
        public SerializableAttachment() {
                super();
        }
        public SerializableAttachment(String name, int age) {
                super();
                this.name = name;
                this.age = age;
        }
        @Override
        public String toString() {
                return "name:" + name + ", age" + age;
        }
       
       
       
}

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 赞一个!

查看全部评分

回复 使用道具 举报
我还不会 ,加快脚步了
回复 使用道具 举报
我还不会呢,马上赶上...
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马