其他流---对象处理流

时间:2022-07-22
本文章向大家介绍其他流---对象处理流,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

新学习内容

该流做的是对象持久化处理 java.io.Serializable 空接口,向jvm声明,实现了这个接口的对象即可被存储到文件中 transient(译:暂时) 声明不存储到文件中的属性 ObjectInputStream和ObjectOutputStream 对象输入输出流

建立雇员对象:

package cn.hxh.io.other;

public class Employee implements java.io.Serializable {
	private transient String name;
	private double 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;
	}

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

	public Employee() {
		super();
	}

}

进行读取写入完整代码

package cn.hxh.io.other;

import java.io.*;
import java.util.Arrays;

public class ObjectDemo01 {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		write("D:/aa/aa.txt");
		read("D:/aa/aa.txt");
	}
	
	public static void read(String destPath) throws IOException, ClassNotFoundException {
		File dest = new File(destPath);
		ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(dest)));
		Object obj = ois.readObject();
		Employee emp = null;
		if (obj instanceof Employee) emp = (Employee) obj;
		System.out.println(emp.getName());
		System.out.println(emp.getSalary());
		System.out.println(emp.getClass());
		obj = ois.readObject();
		int[] i = null;
		if (obj instanceof int[]) i = (int[]) obj;
		System.out.println(Arrays.toString(i));
		ois.close();
	}
	
	public static void write(String destPath) throws IOException {
		Employee emp = new Employee("aaa", 10000);
		File dest = new File(destPath);
		ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
		oos.writeObject(emp);
		int[] i = {1, 2, 3, 4, 5};
		oos.writeObject(i);
		oos.flush();
		oos.close();
	}
}