zoukankan      html  css  js  c++  java
  • 序列化对象

    实现Serialiable 接口才能进行序列化,标注transient和static的变量会被忽略。

    import java.io.Serializable;
    
    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;
            }
        }
    import java.io.*;
    import java.util.Date;
    
    public class ObjectSaver { 
        /*其中的  D:\objectFile.obj 表示存放序列化对象的文件*/
    
        public static void out(Object object,String filename){
            try {
            OutputStream  file= new FileOutputStream(filename);
             //序列化对象
            ObjectOutputStream out = new ObjectOutputStream(file);
    //        Customer customer = new Customer("王麻子", 24);    
            out.writeObject(object);    //写入customer对象
            out.close();    
            
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
        public static Object in (String filename){
                //反序列化对象
            Object object = null;
            try {
                ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
                 object =  in.readObject();    //读取customer对象
                System.out.println(object);
                in.close();
            
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return object;    
        }
        public static void main(String[] args) throws Exception {
            String filename = "src\objectFile.txt";
            Customer customer = new Customer("王麻子", 24);
                  out(customer,filename);
                      in(filename);
            
    
        }

       另外

  • 相关阅读:
    ASP.NET进阶(3):调用Javascript
    CMS系统模版引擎设计(3):Label基类的设计
    CMS系统模版引擎设计(1):基础类型
    CMS系统模板引擎设计(5):Label应用初探
    Thread系列——WaitHandle
    Thread系列——AutoResetEvent
    关于lock
    仅允许程序运行一个实例代码实现
    Thread系列——ManualResetEvent
    Thread系列——Thread.Join()
  • 原文地址:https://www.cnblogs.com/the-wang/p/7248746.html
Copyright © 2011-2022 走看看