java学习笔记(一)

对象的序列化
对象序列化机制:把内存中的java对象转化成平台无关的二进制流,从而与允许把这种二进制流持久地保存在磁盘上,或者通过网络将这种二进制流传输到另一个网络节点。当其他程序获取了这种二进制流,就可以恢复成原来的java对象

方式:任何实现了serializable接口的对象转化为字节数据,使其在保存和传输时可被还原

以下定义一个Person类,然后实现serializable接口,再通过ObjectOutputStream将对象输出到文本,在用ObjectInputStream从文本中读取Person对象
Person类:
import java.io.Serializable;
public class Person implements Serializable {
	private static final long serialVersionUID = 1L;
	private int id;
	private String name;
    private int age;
    private String address;
    
	public Person(int id, String name, int age, String address) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.address = address;
	}
	public Person() {
		super();
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age
				+ ", address=" + address + "]";
	}
}

ObjectStreamClient类:
package com.jdbc.beta1.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


public class ObjectStreamClient {

	public static void objectToText() {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = new FileOutputStream("person.txt");
			oos = new ObjectOutputStream(fos);
			Person p = new Person(1, "tom", 21, "china");
			Person p1 = new Person(1, "jack", 23, "usa");
			oos.writeObject(p);
			oos.flush();
			oos.writeObject(p1);
			oos.flush();
			oos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(oos!=null){
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public static void objectReadText() {
		FileInputStream fos = null;
		ObjectInputStream ois = null;
		try {
			fos = new FileInputStream("person.txt");
			ois = new ObjectInputStream(fos);
			Person p = (Person) ois.readObject();
			Person p1 = (Person) ois.readObject();
			System.out.println(p);
			System.out.println(p1);
			ois.close();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(ois!=null){
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String[] args) {
		ObjectStreamClient.objectToText();
		ObjectStreamClient.objectReadText();
	}
}

运行后看到生成了person.txt文件,
控制台输出:
Person [id=1, name=tom, age=21, address=china]
Person [id=1, name=jack, age=23, address=usa]


展开阅读全文

没有更多推荐了,返回首页