我的技术博客经常被流氓网站恶意爬取转载。请移步原文:http://www.cnblogs.com/hamhog/p/3558663.html,享受整齐的排版、有效的链接、正确的代码缩进、更好的阅读体验。

【默认格式】

public class MyClass implements Serializable{
...}

序列化:

ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(outputPath)); 
output.writeObject(myObject);

反序列化:

ObjectInputStream input = new ObjectInputStream(new FileInputStream(inputPath));
return (MyClass)input.readObject();

【JSON格式】

使用jackson包。jackson是一个效率非常高的Java JSON包。文档和下载见官网

序列化:

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File(outputPath), myObject);

反序列化:

return mapper.readValue(new File(outputPath), MyClass.class);

【完整测试代码】

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList; import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper; public class Zoo implements Serializable { private static final long serialVersionUID = 1L;
private static ObjectMapper mapper = new ObjectMapper(); public static int maxAnimalCount;
public ArrayList<String> animals; public Zoo() {
animals = new ArrayList<String>();
} public static void setMax(int max){
maxAnimalCount = max;
} /**
* Add an animal to animals Array.
* @param animalName
*/
public void addAnimal(String animalName){
if (animals.size() < maxAnimalCount)
animals.add(animalName);
} @Override
public String toString(){
return "Zoo: \n animals: " + animals.toString() +
"\n maxAnimalCount: " + maxAnimalCount + "\n";
} /**
* Output standard serialization to file at logPath.
* @param logPath
*/
public void serializeToLog(String logPath) {
ObjectOutputStream output = null;
try
{
output = new ObjectOutputStream(
new FileOutputStream(logPath));
output.writeObject(this);
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* Output JSON serialization(using jackson) to file at logPath.
* @param logPath
*/
public void serializeJSONToLog(String logPath){ try {
mapper.writeValue(new File(logPath), this);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* Standard deserialize a Zoo instance from file at logPath.
* @param logPath
* @return deserialized zoo instance
*/
public static Zoo deserializeFromLog(String logPath) {
ObjectInputStream input = null;
try
{
input =new ObjectInputStream(
new FileInputStream(logPath));
return (Zoo)input.readObject();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
} return null;
} /**
* JSON deserialize a Zoo instance from file at logPath.
* @param logPath
* @return JSON deserialized zoo instance
*/
public static Zoo deserializeJSONFromLog(String logPath){
try {
return mapper.readValue(new File(logPath), Zoo.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} return null;
}
} class ZooSerializeTest {
public static void main(String[] args) {
Zoo zoo1 = new Zoo();
Zoo.setMax(100);
zoo1.addAnimal("hamster");
zoo1.addAnimal("sheep"); zoo1.serializeToLog("zoo1.log"); Zoo zoo2 = new Zoo();
Zoo.setMax(200);
zoo2.addAnimal("tiger"); zoo2.serializeToLog("zoo2.log"); Zoo.setMax(300); //Deserialization
zoo1 = Zoo.deserializeFromLog("zoo1.log");
zoo2 = Zoo.deserializeFromLog("zoo2.log"); System.out.println("zoo1: \n" + zoo1);
System.out.println("zoo2: \n" + zoo2); //Serialize to JSON
zoo1.serializeJSONToLog("zoo1.json");
zoo1 = Zoo.deserializeJSONFromLog("zoo1.json"); System.out.println("zoo1 from json: \n" + zoo1);
}
}

注意到默认的serialize会序列化private的属性,不会序列化静态属性;而jackson不会序列化非public的属性和静态属性。

最新文章

  1. Memcache的增删改查
  2. 【译】PHP的变量实现(给PHP开发者的PHP源码-第三部分)
  3. 在CentOS上部署Asp.Net MVC3的第一次尝试
  4. Mac系统安装jdk和maven
  5. Swift数据类型简介(二)
  6. Jqgrid入门-Jqgrid格式化数据(九)
  7. jsp-3 简单的servlet连接mysql数据库 使用mvc的登录注册
  8. TCP/IP 标志位 SYN ACK RST UTG PSH FIN
  9. 22.Linux-块设备驱动之框架详细分析(详解)
  10. hbase操作(shell 命令,如建表,清空表,增删改查)以及 hbase表存储结构和原理
  11. Ubuntu命令整理
  12. CommonsChunkPlugin
  13. window环境下使用filezilla server搭建ftp服务器
  14. Spring AOP中的JDK和CGLib动态代理哪个效率更高?
  15. app启动过程
  16. linux 下的OpenGL的安装配置
  17. 【map离散&amp;容斥】Ghosts @Codeforces Round #478 (Div. 2) D
  18. Spring启动研究2.AbstractApplicationContext.obtainFreshBeanFactory()研究
  19. Python中使用SMTP发送邮件以及POP收取邮件
  20. Prometheus监控学习笔记之PromQL简单示例

热门文章

  1. 剑指OFFER之从1到n中出现1的次数(九度OJ1373)
  2. java正则表达式入门基础
  3. 软件测试之WEB测试经典总结
  4. HBase in 2013
  5. C#WinForm应用程序实现自动填充网页上的用户名和密码并点击登录按钮【转载】
  6. 大作业 XXX大学 课程管理系统
  7. Supervised Learning-Regression
  8. java_泛型 TreeSet 判断hashcode/length(升序排列)
  9. IIS 之 查看并发连接数
  10. servlet案例