关于数据序列化(2)二进制流示例

时间:2021-07-04 21:44:51

将一个对象保写进2进制流,保存在文件中,然后从文件中恢复对象

问题:

 像这样大家觉的直接writeInt(),writeByt();用来跟客户端通讯和做持久化存在硬盘有什么问题吗
protobuf哪里能看出来是省资源了,他的原理不也是格式化存储吗
难道会比直接写二进制流还省?

/**
 * 序列化
 */
public class Person implements Serializable{

	private String name;
	private int height;

	public Person(String name, int height) {
		super();
		this.name = name;
		this.height = height;
	}
	
	public Person() {
	}
	
	public String getName() {
		return name;
	}

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

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	@Override
	public String toString() {
		return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
	}
}


import com.google.common.collect.Lists;

public class DataTest {

	public static List<Person> parseData(byte [] targetData) {
		List<Person> list = Lists.newArrayList();
		try {
			DataInputStream in = new DataInputStream(new ByteArrayInputStream(targetData));
			int size = in.readByte();
			for(int i=0;i<size;i++){
				Person b = new Person();
				b.setName("李柏然");
				b.setHeight(178);
				list.add(b);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}


	public static byte [] buildData(List<Person> list) {
		try {
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			DataOutputStream out = new DataOutputStream(bout);
			out.writeByte(list.size());
			for(Person r : list){
				out.writeUTF(r.getName());
				out.writeInt(r.getHeight());
			}
			out.flush();
			out.close();
			return (bout.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	
	}
	public static void main(String[] args) throws Exception {
		String fileName = "序列化.os";
//		test1(fileName);
        
		test2(fileName);
        
	}
	/**
	 * 从文件读取对象
	 */
	private static void test2(String fileName) throws Exception {
		byte[] nowData = ByteUtil.getData(fileName);
		List<Person> list = parseData(nowData);
		System.out.println(list);
	}

	/**
	 * 将文件存入文件
	 */
	private static void test1(String fileName) throws FileNotFoundException,
			IOException {
		List<Person> persons = Lists.newArrayList();
		Person p = new Person("李柏然",178);
		Person p2 = new Person("李思雨",168);
		persons.add(p);
		persons.add(p2);
		byte[] data = buildData(persons);
		ByteUtil.writeFile(data, fileName);
	}
}

public class ByteUtil {
	public static byte[] getData(String fileName) throws Exception{
		FileInputStream fis = new FileInputStream(fileName);
        ObjectInputStream ois = new ObjectInputStream(fis);
        byte[] data = (byte[]) ois.readObject();
        ois.close();
        return data;
	}
	
	public static void writeFile(byte[] data, String fileName) throws FileNotFoundException,
			IOException {
		FileOutputStream fos = new FileOutputStream(fileName);
        ObjectOutputStream os= new ObjectOutputStream(fos);
        os.writeObject(data);
        os.close();
	}
}