`
sudalyl
  • 浏览: 100475 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

java序列化与反序列化

阅读更多

 

题目:

 



 

背景:    

     星期六给我班X姐布置了个集合方面的两个简单的题目,虽然布置了自己也没去看,她做的时候问了我下,X姐接受能力很强啊,很快就搞定了,她是

使用简单的字符串写入解析做的,晚上回去后想了想是否可以使用序列化呢,结果当然是肯定的,于是自己动手写了一个。

 

 

 

 Student类:

 

 

/* * @author :LYL
 *@date:2011-4-23
 */
package com.lyl.collection.exercise;

import java.io.Serializable;

//一定要实现Serializable接口,否则无法序列化
public class Student implements Comparable<Student>,Serializable{
	private static final long serialVersionUID = 1L;
	private int number;
	private String name;
	private int score;

	public Student(){}
	
	public Student(int number,String name,int score){
		this.number=number;
		this.name=name;
		this.score=score;
	}
	
	public int getNumber() {
		return number;
	}
	public void setNumber(int number) {
		this.number = number;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	@Override
	public String toString() {
		return "学号:"+this.getNumber()+",姓名:"+this.getName()+",成绩:"+this.getScore();
	}

	@Override
	public int compareTo(Student student) {
		if (this.getNumber()>student.getNumber()) {
			return 1;
		}
		if(this.getNumber()<student.getNumber()){
			return -1;
		}
		return 0;
	}
}
 

 

SaveObjectHelper:

 

/**
 * 将对象序列化输出到文件
 * @author :LYL
 *@date:2011-4-23
 */
package com.lyl.collection.exercise;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SaveObjectHelper {
	//对象数组
	private Object[] objects;
	//文件路径
	private String path;
	public SaveObjectHelper(Object[] objects,String path){
		this.objects=objects;
		this.path=path;
	}
	public boolean saveFile(){
		boolean flag=false;
		File file=new File(this.path);
		ObjectOutputStream oos=null;
		try {
			//对象输出流
			oos=new ObjectOutputStream(new FileOutputStream(file));
			oos.writeObject(this.objects);
			//成功复制true
			flag=true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			//一定要关闭流
			if(oos!=null){
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}
}

 

 

GetObjectHelper:

 

/**
 * 将对象反序列化
 * @author :LYL
 *@date:2011-4-23
 */
package com.lyl.collection.exercise;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class GetObjectHelper {
	//文件路径
	String filepath;
	public GetObjectHelper(String filepath){
		this.filepath=filepath;
	}

	public Object getObject(){
		File file=new File(this.filepath);
		Object objects=null;
		ObjectInputStream ois=null;
		try {
			//获得对象流
			ois=new ObjectInputStream(new FileInputStream(file));
			objects=ois.readObject();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			//关闭对象输入流
			if(ois!=null){
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return objects;
	}
}

 

 

StudentOper

 

/**
 * @author :LYL
 *@date:2011-4-23
 *保存对象,将对象排序
 */
package com.lyl.collection.exercise;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StudentOper {
	public static void main(String[] args) {
		//首先创建五个学生对象
		Student stu1=new Student(1, "yy", 90);
		Student stu2=new Student(5, "ym", 89);
		Student stu3=new Student(4, "mr", 99);
		Student stu4=new Student(6, "miss", 100);
		Student stu5=new Student(7, "mess", 98);
		//创建一个学生对象数组
		Student[] students={stu1,stu2,stu3,stu4,stu5};
		//将对象数组序列化,保存到本地
		String filepath="D:"+File.separator+"students.ser";
		SaveObjectHelper soh=new SaveObjectHelper(students,filepath);
		boolean success=soh.saveFile();
		if(success){
			System.out.println("对象保存成功!");
		}else{
			System.out.println("对象保存失败!");
		}
		
		List<Student> stulist=new ArrayList<Student>();
		stulist.add(stu1);
		stulist.add(stu2);
		stulist.add(stu3);
		stulist.add(stu4);
		stulist.add(stu5);
		Collections.sort(stulist);  
		System.out.println(stulist);
	}
}

 

 

QueryInfo:

 

/**
 * 根据学号查询
 * @author :LYL
 *@date:2011-4-23
 */
package com.lyl.collection.exercise;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class QueryInfo {
	public static void main(String[] args) {
		String filepath="D:"+File.separator+"students.ser";
		//获得对象数组
		GetObjectHelper goh=new GetObjectHelper(filepath);
		Object object=goh.getObject();
		//由于我们知道就是student类型的数组,所以对其强制类型转换
		Student[] students=(Student[])object;

		/*测试是否读出成功
		 * for(int i=0;i<students.length;i++){
			System.out.println(students[i]);
		}*/

		while(true){
			System.out.println("学生信息查询系统,输入exit可以退出系统!");
			Student query=null;
			int userinput=0;
			System.out.println("请输入学号:");
			//获得用户输入
			BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
			//用户输入的临时变量
			String temp;
			try {
				temp = br.readLine();
				//如果用户输入的是exit,则退出系统
				if(temp.equals("exit")){
					System.out.println("系统已退出!");
					System.exit(0);
				}
				//先判断是否为已经输入值
				if(temp.length()>0){
					try {
						//将字符串转化为int,如果不能转化则跳到catch处
						userinput=Integer.parseInt(temp);
						//循环取出student对象
						for(int i=0;i<students.length;i++){
							//相等我们就将这个对象赋给query,并且跳出for循环
							if(userinput==students[i].getNumber()){
								query=students[i];
								break;
							}
						}
						//判断经过循环之后query中是否有值
						if(query!=null){
							System.out.println(query);
						}else {
							System.out.println("查无此人!请重新输入!");
						}
					} catch (Exception e) {
						System.out.println("请输入数字");
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			//为了与上一结果空格一行
			System.out.println();
		}

	}
}
 

 

这样就实现了那两道题目了,大家也可以使用其他方法试试,题目虽简单,但是我们可以让其变得不简单,使用各种手段解决。

  • 大小: 37.5 KB
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics