对象文件处理流

package com.cyj.Other;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


/**
 * 对象文件处理流
 * 序列化和反序列化必须要是实现空接口java.io.serializble
 * 用transient区别是否需要序列化对象的属性
 * 对象读取强制转换
 * @author Chyjrily
 *
 */
public class ObjectBase {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		seri("E:\\爱情公寓全集\\Japen.txt");
		read("E:\\爱情公寓全集\\Japen.txt");
	}
	
	public static void read(String destPath) throws IOException, ClassNotFoundException {
			
			//建立联系
			File dest = new File(destPath);
			
			//选择流
			ObjectInputStream dis = new ObjectInputStream(
					new BufferedInputStream(new FileInputStream(dest))
					);
			
			//操作 按顺序写出,为读取做准备
			Object obj = dis.readObject();
			if(obj instanceof Cake) {
				Cake ck = (Cake) obj;  //强制转换对象类型
				System.out.println(ck.getName()); 
				System.out.println(ck.getPrice());
			}
			
			obj = dis.readObject();
			int[] arr = (int[]) obj; //强制转换对象类型
			
			System.out.println(arr);
			dis.close();
		}
	
	 
	/**
	 * 序列化
	 * @param destPath
	 * @throws IOException
	 */
	public static void seri(String destPath) throws IOException {
		
		//建立联系
		Cake ck = new Cake("老婆饼",2,100);
		int[] arr = {1,2,3,4,5};  //数组也是对象
		
		File dest = new File(destPath);
		
		//选择流
		ObjectOutputStream dos = new ObjectOutputStream(
				new BufferedOutputStream(new FileOutputStream(dest))
				);
		
		//操作 按顺序写出,为读取做准备
		dos.writeObject(ck);
		dos.writeObject(arr);
		
		dos.flush();//强制刷出
		dos.close();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42036616/article/details/81012419