日志文章

2019-12-24 aflfte2011

对象流的使用

package com.aflfte.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

/**
 * 对象流的使用
 * 1.先写入后读取
 * 2.读取顺序必须与写入顺序保持一致
 * 3.对象流需要序列化
 * 4.不是所有的对象都可以序列化 必须实现接口Serializable
 *
 *
 * ObjectOutputStream //对象输出流
 * ObjectInputStream //对象输入流
 * @author root
 *
 */
public class ObjectTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        ObjectOutputStream dos=new ObjectOutputStream(new BufferedOutputStream(baos));
        dos.writeUTF("编码辛酸泪");
        dos.writeInt(18);
        dos.writeBoolean(false);
        dos.writeChar('a');
        dos.writeObject("谁解其中味");
        dos.writeObject(new Date());
        Employee emp=new Employee("马云",400);
        dos.writeObject(emp);
        dos.flush();
        byte[] datas=baos.toByteArray();
        ObjectInputStream dis=new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
        String str=dis.readUTF();
        int in=dis.readInt();
        boolean bl=dis.readBoolean();
        char cha=dis.readChar();
        Object ob=dis.readObject();
        Object date=dis.readObject();
        Object employee=dis.readObject();
        System.out.println(str+"|"+in+"|"+bl+"|"+cha+"|"+ob);
        if(str instanceof String) {
            String strobj=(String)str;
            System.out.println(strobj);
        }
        if(date instanceof Date) {
            Date da=(Date)date;
            System.out.println(da);
        }
        if(employee instanceof Employee) {
            Employee em=(Employee)employee;
            System.out.println(em.getName()+"-->"+em.getSalary());
        }
    }
}
class Employee implements java.io.Serializable{
    private String name;
    private transient double salary;//加上transient表示该数据不需要序列化
    
    public Employee() {
        super();
    }

    public Employee(String name, double salary) {
        super();
        this.name = name;
        this.salary = salary;
    }

    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;
    }
    
}

« 打印流的使用 | 数据流的使用»