欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 序列化和反序列化(针对字符串的例子)

程序员文章站 2022-03-01 21:44:33
...
1.前言.
   摘自:http://blog.csdn.net/linminqin/article/details/7654276
2.例子.
package lmiky.test.obj;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SerTest {

	/**
	 * 方法说明
	 * @author lmq0382 
	 * @date 2012-6-11
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("number", "123");
		map.put("name", "test");
		list.add(map);
		HashMap<String, String> map2 = new HashMap<String, String>();
		map2.put("number", "1232");
		map2.put("name", "test2");
		list.add(map2);
		
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
		objectOutputStream.writeObject(list);  
		String serStr = byteArrayOutputStream.toString("ISO-8859-1");
		serStr = java.net.URLEncoder.encode(serStr, "UTF-8");
		
		objectOutputStream.close();
		byteArrayOutputStream.close();
		
		System.out.println(serStr);
				
		String redStr = java.net.URLDecoder.decode(serStr, "UTF-8");
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1"));
		ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); 
		List<HashMap<String, String>> newList = (List<HashMap<String, String>>)objectInputStream.readObject(); 
		objectInputStream.close();
		byteArrayInputStream.close();
		

		for(Map m : newList) {
			System.out.println(m.get("number") + " " + m.get("name"));
		}
	}

}