初尝Java序列化/反序列化对象

看个类:

package com.wjy.bytes;

import java.io.Serializable;

public class ObjTest implements Serializable{
    private int age;
    private String name;
    public ObjTest(int age, String name) {
        super();
        this.age = age;
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}

 

序列化和反序列化过程:

package com.wjy.bytes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;



public class ByteArrayTest {
    
    public static void main(String args[]){
          //序列化过程
//        
//        ObjTest obj=new ObjTest(23, "wjy");
//        try {
//            ObjectOutputStream outputStream=new ObjectOutputStream(new FileOutputStream(new File("./file/model.obj")));
//            outputStream.writeObject(obj);
//            outputStream.close();
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        

//反序列化过程 //        try {
//            ObjectInputStream inputStream=new ObjectInputStream(new FileInputStream(new File("./file/model.obj")));
//            ObjTest obj=(ObjTest)inputStream.readObject();
//            
//            System.out.println(obj.getAge());
//            System.out.println(obj.getName());
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (ClassNotFoundException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        
    }
}

 

 

 

 

你可能感兴趣的:(java序列化)