java序列化和反序列化简单案例
java序列化和反序列化简单案例
shikaiJack 发表于1年前
java序列化和反序列化简单案例
  • 发表于 1年前
  • 阅读 5
  • 收藏 0
  • 点赞 0
  • 评论 0
摘要: 使用序列化和反序列化实现集合对象的存储与读取使用了IO流相关知识使用了dom4j提供的jar包
public class XmlSerializer {
	
	@SuppressWarnings("rawtypes")
    //序列化
	public void serializer(File file,Object object){
		try {
			OutputStream os = new FileOutputStream(file);
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "utf-8"));
			bw.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
			if(object instanceof Collection){//判断是否为集合对象
				Class<?> clazz = object.getClass(); 
				bw.write(String.format("<Collection type=\"%s\">\n", clazz.getName()));
				Method method = clazz.getMethod("iterator");
				Iterator ite = (Iterator) method.invoke(object);
				while(ite.hasNext()){
					Object o = ite.next();
					bw.write(getObject(o));
					bw.newLine();
				}
				bw.write("</Collection>");
				
			}else{
				bw.write(getObject(object));//将对象序列化到指定的文件
			}
			bw.flush();
			bw.close();
			os.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    //反序列化
	@SuppressWarnings({ "unchecked", "static-access" })
	public <T> T deserializer(File file,Class<?> clazz){
		SAXReader reader = new SAXReader();
		Document doc=null;
		T obj=null;
		try {
			doc = reader.read(file);
			obj = (T) clazz.newInstance();
			if(obj instanceof Collection){
				for(Iterator<Element> ite = doc.getRootElement().elementIterator();ite.hasNext();){
					Element element = ite.next();
					Class<?> itemClass = clazz.forName(element.attributeValue("type"));
					Object o = itemClass.newInstance();
					getDeserializer(element,o,itemClass);
					Method addMethod = clazz.getMethod("add",Object.class);
					addMethod.invoke(obj, o);//将对象添加到集合中
				}
			}else{
                //获取xml文件中标签的属性type的值
				Class<?> cla = clazz.forName(doc.getRootElement().attributeValue("type"));
				getDeserializer(doc.getRootElement(),obj,cla);
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
		
	}
	@SuppressWarnings("unchecked")
    //获得单个对象的所有属性并未属性设置值
	private void getDeserializer(Element rootElement, Object object, Class<?> cla) {
		for(Iterator<Element> ite = rootElement.elementIterator();ite.hasNext();){
			Element ele = ite.next();
			try {
				Field field = cla.getDeclaredField(ele.getName());
				field.setAccessible(true);
				getField(field,object,ele.getText());
				
			} catch (NoSuchFieldException | SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
    //将值设置到属性中
	private void getField(Field field, Object object,String value) {
		Class<?> type = field.getType();
		try {
			if(type==int.class){				
				field.set(object, Integer.parseInt(value));				
			}else if(type==double.class){
				field.set(object, Double.parseDouble(value));		
			}else if(type==String.class){
				field.set(object, value);		
			}
		} catch (NumberFormatException  e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    //将对象写入到xml中
	private String getObject(Object object) {
		Class<?> clazz = object.getClass();
		String string="";
		string += String.format("<%s type=\"%s\">\n", getSimpleName(clazz.getName()),clazz.getName());
		Field[] fields = clazz.getDeclaredFields();
		for(Field field:fields){
			field.setAccessible(true);
			try {
				string += String.format("\t<%s>%s</%s>\n", field.getName(),field.get(object),field.getName());
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		string += String.format("</%s>\n", getSimpleName(clazz.getName()));
		return string;
	}
    
	private String getSimpleName(String name) {
		// TODO Auto-generated method stub
		return name.substring(name.lastIndexOf(".")+1);
	}

}

 

public class Student {
	private String name;
	private int age;
	
	public Student(){}
	
	public Student(String name,int age){
		this.name=name;
		this.age=age;
	}
    //相应的get和set方法省略
}
public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		File file=new File("e:\\student.xml");
		XmlSerializer serializer=new XmlSerializer();
//		List<Student> students=new ArrayList<Student>();
//		students.add(new Student("张三",20) );
//		students.add(new Student("李四",22) );
//		Student stu = new Student("张三",20);
//		serializer.serializer(file, stu);
//		serializer.serializer(file, students);
//		Student stu=serializer.deserializer(file,Student.class);
//		stu.hello();
		List<Student> studentList=serializer.deserializer(file, ArrayList.class);
		for(Student student:studentList){
			student.hello();
		}
     }
}

 

共有 人打赏支持
粉丝 0
博文 1
码字总数 685
×
shikaiJack
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: