三十二,对象序列化

1.对象序列化定义

将一个对象保存为二进制的数据流.一个对象要想序列化,必须实现Serializable接口.此接口没有任何方法,只是一个标识接口,类似的还有Clonable接口.

一个对象要序列化还需要依靠ObjectOutputStream类和ObjectInputStream.

2.对象序列化

序列化类示例:

package com.ares.serdemo;
import java.io.Serializable;

public class Person implements Serializable {
	private String name;
	private int age;
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public String toString() {
		return "姓名:" + this.name + ",年龄:" + this.age;
	}
}




示例:

package com.ares.serdemo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class ObjectOutputStreamDemo {
	public static void main(String[] args) throws Exception {
		File file = new File("d:" + File.separator + "person.ser");
		ObjectOutputStream oos = null;
		oos = new ObjectOutputStream(new FileOutputStream(file));
		Person per = new Person("张三", 30);
		oos.writeObject(per) ;
		oos.close() ;
	}
}



3.反序列化

示例:

package com.ares.serdemo;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class ObjectInputStreamDemo {
	public static void main(String[] args) throws Exception {
		File file = new File("d:" + File.separator + "person.ser");
		ObjectInputStream ois = null;
		ois = new ObjectInputStream(new FileInputStream(file));
		Object obj = ois.readObject();
		Person per = (Person) obj;
   //向下转型
		System.out.println(per);
	}
}

备注:如果类中的某个属性不希望被序列化,则可以使用transient关键字申明.


4.一组对象的序列化

示例:

package com.ares.serdemo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ArraySerDemo {
	public static void main(String[] args) throws Exception {
		Person per[] = { new Person("张三", 30), new Person("李四", 31),
				new Person("王五", 32) };
		ser(per);
		Person p[] = (Person[]) dser();	
		print(p) ;
	}
	public static void ser(Object obj) throws Exception {
		File file = new File("d:" + File.separator + "person.ser");
		ObjectOutputStream oos = null;
		oos = new ObjectOutputStream(new FileOutputStream(file));
		oos.writeObject(obj);
		oos.close();
	}
	public static Object dser() throws Exception {
		Object temp = null;
		File file = new File("d:" + File.separator + "person.ser");
		ObjectInputStream ois = null;
		ois = new ObjectInputStream(new FileInputStream(file));
		temp = ois.readObject();
		return temp;
	}
	public static void print(Person per[]) {
		for (Person p : per) {
			System.out.println(p);
		}
	}
}



5.序列化完成单人信息的增删改查操作

示例:

菜单代码:

package com.ares.persondemo;
public class Menu { // 显示菜单
	public Menu() {
		while (true) {
			this.show();
		}
	}
	public void show() {
		System.out.println("====== Xxx 系统 ========");
		System.out.println("    [1]、增加数据   ");
		System.out.println("    [2]、查看数据   ");
		System.out.println("    [3]、修改数据   ");
		System.out.println("    [4]、删除数据   ");
		System.out.println("    [0]、退出系统   ");
		InputData input = new InputData();
		int choose = input.getInt("\n\n请选择:", "输入错误,重新输入,");
		switch (choose) {
		case 1: {
			Operate.add();
			break;
		}
		case 2: {
			Operate.find();
			break;
		}
		case 3: {
			Operate.update();
			break;
		}
		case 4: {
			Operate.delete();
			break;
		}
		case 0: {
			System.exit(1);
		}
		default: {
			System.out.println("无效的选项");
		}
		}
	}
}




FileOperator代码:

package com.ares.persondemo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class FileOperate {
	private File file = null;
	public FileOperate(String path) {
		this.file = new File(path); // 从外部指定操作的文件路径
	}

	public void save(Object obj) throws Exception {
		ObjectOutputStream oos = null;
		oos = new ObjectOutputStream(new FileOutputStream(file));
		oos.writeObject(obj);
		oos.close();
	}

	public Object load() throws Exception {
		Object temp = null;
		ObjectInputStream ois = null;
		ois = new ObjectInputStream(new FileInputStream(file));
		temp = ois.readObject();
		return temp;
	}
}



Operate代码:

package com.ares.persondemo;

public class Operate {
	public static void add() {
		InputData input = new InputData();
		String name = input.getString("输入姓名:");
		int age = input.getInt("输入年龄:", "输入的不是数字,");
		Person per = new Person(name, age);
		FileOperate operate = new FileOperate("d:\\pers.ser");
		try {
			operate.save(per);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void find() {
		FileOperate operate = new FileOperate("d:\\pers.ser");
		Person per = null;
		try {
			per = (Person) operate.load();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (per != null) {
			System.out.println(per);
		} else {
			System.out.println("没有任何的数据。");
		}
	}

	public static void update() {
  //修改对象的属性
		FileOperate operate = new FileOperate("d:\\pers.ser");
		Person per = null;
		try {
			per = (Person) operate.load();
		} catch (Exception e) {
			e.printStackTrace();
		}
		InputData input = new InputData();
		String name = input.getString("输入姓名(原姓名:" + per.getName() + "):");
		int age = input.getInt("输入年龄(原年龄:" + per.getAge() + "):", "输入的不是数字,");
		per = new Person(name, age);
		operate = new FileOperate("d:\\pers.ser");
		try {
			operate.save(per);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void delete() {
		FileOperate operate = new FileOperate("d:\\pers.ser");
		try {
			operate.save(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



Person类代码:

package com.ares.persondemo;
import java.io.Serializable;
public class Person implements Serializable {
	private String name;
	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;
	}
	private int age;
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public String toString() {
		return "姓名:" + this.name + ",年龄:" + this.age;
	}
}



Test类代码:

package com.ares.persondemo;
public class TestMenu { // 显示菜单
	public static void main(String args[]) {
		new Menu();
	}
}




6.投票系统示例

示例:

Menu类代码:

package com.ares.demo;
// 循环选择\修改选票\显示全部的信息
public class Menu {
	private Student stu[] = { new Student(1, "张三", 0), new Student(2, "李四", 1),
			new Student(3, "王五", 0), new Student(4, "刘六", 0) };
	public Menu() {
		Operate oper = new Operate(stu);
		// 1、显示出全部的数据
		oper.list();
		// 2、调用投票
		while (oper.vote()) {
			;
		}
		// 3、列出全部的票数
		oper.list();
		// 4、求出结果
		oper.result() ;
	}
}



Student:

package com.ares.demo;

public class Student implements Comparable<Student> {
    //实现Comparable接口
	private int stuno;
	private String name;
	private int count;
	public Student() {
		super();
	}
	public Student(int stuno, String name, int count) {
		super();
		this.stuno = stuno;
		this.name = name;
		this.count = count;
	}
	public int getStuno() {
		return stuno;
	}
	public void setStuno(int stuno) {
		this.stuno = stuno;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}

	public int compareTo(Student stu) {
   //覆写比较方法
		if (this.count > stu.count) {
			return -1;
		} else if (this.count < stu.count) {
			return 1;
		} else {
			return 0;
		}
	}
}



Operate类代码:

package com.ares.demo;
public class Operate {
	private Student stu[] = null;
	private InputData input = null;
	public Operate(Student stu[]) {
		this.stu = stu;// 对象数组的内容由外部决定
		this.input = new InputData();
	}
	public void list() {
		for (int i = 0; i < this.stu.length; i++) {
			System.out.println(this.stu[i].getStuno() + ":"
					+ this.stu[i].getName() + "【" + this.stu[i].getCount()
					+ "票】");
		}
	}
	public boolean vote() {// 完成具体的投票功能
		boolean flag = true;
		int stuno = this.input.getInt("请输入班长候选人代号(数字0结束):",
				"此选票无效,请输入正确的候选人代号!");
		switch (stuno) {
		case 1: {
			this.stu[0].setCount(this.stu[0].getCount() + 1);// 修改选票
			break;
		}
		case 2: {
			this.stu[1].setCount(this.stu[1].getCount() + 1);// 修改选票
			break;
		}
		case 3: {
			this.stu[2].setCount(this.stu[2].getCount() + 1);// 修改选票
			break;
		}
		case 4: {
			this.stu[3].setCount(this.stu[3].getCount() + 1);// 修改选票
			break;
		}
		case 0: {
			flag = false;
			break;
		}
		default: {
			System.out.println("此选票无效,请输入正确的候选人代号!");
		}
		}
		return flag;
	}
	public void result() {
		java.util.Arrays.sort(this.stu);// 对象数组排序
		System.out.println("投票最终结果:" + this.stu[0].getName() + "同学,最后以"
				+ this.stu[0].getCount() + "票当选班长!");
	}
}



InputData类代码:

package com.ares.demo;
    //可以作为一个工具类保存.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class InputData {
	private BufferedReader buf = null;
	public InputData() {
		this.buf = new BufferedReader(new InputStreamReader(System.in));
	}
	public String getString(String info) {
		String str = null;
		System.out.print(info);// 打印提示信息
		try {
			str = this.buf.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}
	public int getInt(String info, String err) {
		int temp = 0;
		boolean flag = true;// 定义一个标志位
		while (flag) {
			String str = this.getString(info);
			if (str.matches("\\d+")) {
				temp = Integer.parseInt(str);
				flag = false;// 退出循环
			} else {
				System.out.print(err);
			}
		}
		return temp;
	}
	public float getFloat(String info, String err) {
		float temp = 0.0f;
		boolean flag = true;// 定义一个标志位
		while (flag) {
			String str = this.getString(info);
			if (str.matches("\\d+.?\\d+")) {
				temp = Float.parseFloat(str);
				flag = false;// 退出循环
			} else {
				System.out.print(err);
			}
		}
		return temp;
	}
	public char getChar(String info, String err) {
		char temp = ' ';
		boolean flag = true;// 定义一个标志位
		while (flag) {
			String str = this.getString(info);
			if (str.matches("\\w")) {
				temp = str.charAt(0);
				flag = false;// 退出循环
			} else {
				System.out.print(err);
			}
		}
		return temp;
	}
	public Date getDate(String info, String err) {
		Date temp = null ;
		boolean flag = true;// 定义一个标志位
		while (flag) {
			String str = this.getString(info);
			if (str.matches("\\d{4}-\\d{2}-\\d{2}")) {
				try {
					temp = new SimpleDateFormat("yyyy-MM-dd").parse(str) ;
				} catch (ParseException e) {
					System.out.print(err) ;
				}
				flag = false;// 退出循环
			} else {
				System.out.print(err);
			}
		}
		return temp;
	}
}



Test类代码:

package com.ares.demo;
public class Test {
	public static void main(String[] args) {
		new Menu();
	}
}








20150512


JAVA学习笔记系列

--------------------------------------------

                    联系方式

--------------------------------------------

        Weibo: ARESXIONG

        E-Mail: [email protected]

------------------------------------------------



你可能感兴趣的:(Serializable,transient,对象序列化,投票系统)