java序列化與反序列化操作實例分析
更新時間:2016年10月26日 11:34:33 作者:Wallace
這篇文章主要介紹了java序列化與反序列化操作,結合實例形式分析了java序列化與反序列化的概念與具體實現(xiàn)技巧,需要的朋友可以參考下
本文實例分析了java序列化與反序列化操作。分享給大家供大家參考,具體如下:
概述:
Java序列化是指把Java對象轉換為字節(jié)序列的過程;而Java反序列化是指把字節(jié)序列恢復為Java對象的過程。
示例代碼:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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 java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:/objectFile.obj"));
Customer customer = new Customer("中國人",23);
out.writeObject("你好!");
out.writeObject(new Date());
out.writeObject(customer);
out.writeInt(123);
List list = new ArrayList();
int i =0 ;
while(i<100) {
Customer customer2 = new Customer("中國人",i);
list.add(customer2);
i++;
}
HashMap hashMap = new HashMap();
hashMap.put("customer", list);
out.writeObject(hashMap);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:/objectFile.obj"));
System.out.println("obj1= " + (String) in.readObject());
System.out.println("obj2= " + (Date) in.readObject());
Customer obj3 = (Customer) in.readObject();
System.out.println("obj3= " + obj3);
int obj4 = in.readInt();
System.out.println("obj4= " + obj4);
Object obj5 = in.readObject();
System.out.println(obj5);
HashMap hash_map = (HashMap)obj5;
List l = (List) hash_map.get("customer");
System.out.println("size: " + l.size());
for(int ii=0; ii<l.size() -1 ; ii++) {
Customer c = (Customer)l.get(ii);
System.out.println(c.getName());
System.out.println(c.getAge());
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Customer implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Customer(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "name=" + name + ", age=" + age;
}
}
希望本文所述對大家java程序設計有所幫助。
相關文章
SpringMVC4+MyBatis+SQL Server2014實現(xiàn)數(shù)據(jù)庫讀寫分離
這篇文章主要介紹了SpringMVC4+MyBatis+SQL Server2014實現(xiàn)讀寫分離,需要的朋友可以參考下2017-04-04
springboot+webmagic實現(xiàn)java爬蟲jdbc及mysql的方法
今天小編就為大家分享一篇springboot+webmagic實現(xiàn)java爬蟲jdbc及mysql的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
Spring?Boot整合持久層之JdbcTemplate多數(shù)據(jù)源
持久層是JavaEE中訪問數(shù)據(jù)庫的核心操作,SpringBoot中對常見的持久層框架都提供了自動化配置,例如JdbcTemplate、JPA 等,MyBatis 的自動化配置則是MyBatis官方提供的。接下來分別向讀者介紹Spring Boot整合這持久層技術中的整合JdbcTemplate2022-08-08
eclipse+maven+spring mvc項目基本搭建過程
這篇文章主要介紹了eclipse+maven+spring mvc項目基本搭建過程,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09

