java 对象流的使用

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.TreeMap;

public class ObjectIO {

	public static void main(String[] args) {
		
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;
		
		//对象存放文件路径
		String object_data_path = "D:/Desktop/object.data";
		try {
			oos = new ObjectOutputStream(new FileOutputStream(object_data_path));
			
			//创建2个student对象,并放进map集合中。
			Student student1 = new Student();
			student1.setId("001");
			student1.setName("张三");
			
			Student student2 = new Student();
			student2.setId("002");
			student2.setName("李四");
			
			TreeMap<String, Student> treeMap = new TreeMap<String, Student>();
			treeMap.put(student1.getId(), student1);
			treeMap.put(student2.getId(), student2);
			
			//将集合map通过对象输出流,保存至文件系统中。
			oos.writeObject(treeMap);
			
			//通过对象输入流将文件系统中的对象读入内存。
			ois = new ObjectInputStream(new FileInputStream(object_data_path));
			TreeMap<String, Student> getMap = (TreeMap<String, Student>) ois.readObject();
			
			//打印从对象输入流读入的对象信息
			System.out.println(getMap.get("001").getName());
			System.out.println(getMap.get("002").getName());
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			
			//关闭输入流、输出流资源
			if(oos != null){
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(ois != null){
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

//Student 必须实现序列化接口
class Student implements Serializable{
	
	private static final long serialVersionUID = 1L;
	private String id;
	private String name;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

 

输出结果:

 

张三
李四

 

生成的data文件内容:


java 对象流的使用_第1张图片
 

 

你可能感兴趣的:(java)