JAVA io流笔记09 对象处理流

package FileText;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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;

//对象处理流 
//反序列化 :输入流 ObjectInputStream   主要方法:readObject()
//序列化:输出流 ObjectOutputStream    主要方法:writeObject()

//注意: 先序列化后反序列化,并且序列化,反序列化顺序必须一致
//并非所有对象都可以实现序列化 ,必需继承 java.io.Serializable  /或者直接继承Serializable
//并非所有属性都必须序列化,不想序列化的可以使用transient

public class ObjectInputStream09 {
public static void main(String args[]) throws IOException, ClassNotFoundException{
    change();
}
public static void change() throws ClassNotFoundException, IOException{
    Employee emp = new Employee("player",100000);
    //创建源
    File file = new File("D:/text/dd/ObjectText.txt");
    //选择流
    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
    out.writeObject(emp);
    out.flush();
    
    getchange(file);
}

public static void getchange(File file) throws ClassNotFoundException{
    try {
        ObjectInputStream input = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
        Object obj = input.readObject();
        if(obj instanceof Employee){
            Employee emp =(Employee)obj;
            
            System.out.println(emp.getName());
            System.out.println(emp.getSalary());  
            //输出结果为null   100000.0//因为name使用了 transient 所以并未序列化                                           
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

class Employee implements  java.io.Serializable{          //例子
    private transient String name = "wu";   //不想序列化的属性
    private double salary = 100000;
    //生成get,set,方法 以及带参构造,无参构造
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public Employee(String name, double salary) {
        super();
        this.name = name;
        this.salary = salary;
    }
    public Employee() {
        super();
    }
    
}

猜你喜欢

转载自blog.csdn.net/qq_40302611/article/details/85207927