Java基礎——IO流、序列化和反序列化

 

 

package com.xupk.serialize;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

/***
 * 將對象數組序列化到硬盤文件中,再反序列化回來
 * 
 * @author xupk
 * 
 */
public class ObjStream {

	public static void main(String[] args) {
		Person p1 = new Person("xupk", "男", 18, new Car("alue", 166));
		Person p2 = new Person("xupk", "男", 28, new Car("blue", 266));
		Person p3 = new Person("xupk", "男", 38, new Car("clue", 366));
		Person[] ps = new Person[] { p1, p2, p3 };
		String path = "C:/workspace/eclipse01/IOPrj";
		String fileName = "p2.txt";
		File file = ser(ps, path, fileName);
		System.out.println("name: " + file.getName());
		System.out.println("parent: " + file.getParent());
		System.out.println("parentFile: " + file.getParentFile());
		System.out.println("path: " + file.getPath());
		System.out.println("absolutePath: " + file.getAbsolutePath());
		System.out.println("absoluteFile: " + file.getAbsoluteFile());
		Person[] pp = dser(file);
		for (Person person : pp) {
			System.out.println(person);
		}
	}

	/***
	 * 序列化對象,將對象輸出到文件中
	 * @param ps
	 * @param path 文件路徑
	 * @param fileName 文件名
	 * @return 保存序列化對象的文件
	 */
	private static <T extends Serializable> File ser(T ps, String path,
			String fileName) {
		OutputStream outs = null;
		ObjectOutputStream out = null;
		File file = new File(path, fileName);
		//如果指定路徑的文件不存在,就新建一個文件
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			outs = new FileOutputStream(file);//從file中讀取文件字節輸出流
			out = new ObjectOutputStream(outs);//將輸出流轉成對象字節輸出流
			out.writeObject(ps);//把對象寫到輸出流中
		} catch (Exception e) {
		} finally {
			try {
				outs.close();
				out.close();
			} catch (Exception e2) {
			}
		}
		return file;
	}

	/***
	 * 反序列化對象,從文件中讀取對象
	 * 
	 * @param file 從file中讀取數據
	 * @return 返回反序列化後的對象
	 */
	@SuppressWarnings("unchecked")
	private static <T extends Serializable> T dser(File file) {
		if (!file.exists()) {
			try {
				throw new FileNotFoundException("");
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		InputStream ins = null;
		ObjectInputStream in = null;
		try {
			ins = new FileInputStream(file);
			in = new ObjectInputStream(ins);
			return (T) in.readObject();
		} catch (Exception e) {
		} finally {
			try {
				ins.close();
				in.close();
			} catch (Exception e2) {
			}
		}
		return null;
	}

}

 

package com.xupk.serialize;

import java.io.Serializable;

public class Person implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8350010615659256735L;
	private String name;
	private String sex;
	private int age;
	private Car car;

	public Person(String name, String sex, int age, Car car) {
		super();
		this.name = name;
		this.sex = sex;
		this.age = age;
		this.car = car;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Car getCar() {
		return car;
	}

	public void setCar(Car car) {
		this.car = car;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", sex=" + sex + ", age=" + age
				+ ", car=" + car + "]";
	}

}

 

package com.xupk.serialize;

import java.io.Serializable;

/**
 * @author xupk
 * 
 */
public class Car implements Serializable{

	
	/**
	 * 
	 */
	private static final long serialVersionUID = -555269900556154294L;

	public Car(String color, int maxSpeed) {
		super();
		this.color = color;
		this.maxSpeed = maxSpeed;
	}

	@Override
	public String toString() {
		return "Car [color=" + color + ", maxSpeed=" + maxSpeed + "]";
	}

	private String color;
	private int maxSpeed;

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public int getMaxSpeed() {
		return maxSpeed;
	}

	public void setMaxSpeed(int maxSpeed) {
		this.maxSpeed = maxSpeed;
	}

}


值得注意的是,序列化的類都要實現Serializable接口,如果不是,那麼將無法序列化。上面的ObjStream類中,兩個方法我都用了泛型,有一句<T extends Serializable>就是指定序列化的類必須要實現Serializable接口的,不然編譯期都會報錯了。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章