Java对象序列化输入输出
在网上看到一篇有关于对象序列化的代码,自己仿着写了把
在Java中,entity通过implements Serializable,然后使用ObjectInputStream和ObjectOutputStream把象序列化输入输出
package com.formain.lyy.service.util.serializable; import java.io.Serializable; import java.util.Date; @SuppressWarnings("serial") public class PeoperEntity implements Serializable{ private String name; //姓名 private Integer age; //年龄 private String gender; //性别 private Date birthday; //出生年月日 @Override public String toString() { return "PeoperEntity [name=" + name + ", age=" + age + ", gender=" + gender + ", birthday=" + birthday + "]"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
public static void main(String[] args) { String filename = "peoperEntity.ser"; PeoperEntity peoperEntity = new PeoperEntity(); peoperEntity.setAge(50); peoperEntity.setGender("男"); peoperEntity.setName("张三"); ArrayList<PeoperEntity> arrayList = new ArrayList<PeoperEntity>(); arrayList.add(peoperEntity); try { SerializableUtils.serializable(arrayList, filename); } catch (Exception e) { e.printStackTrace(); } System.out.println("peoperEntity :\t"+peoperEntity.toString()); ArrayList<PeoperEntity> peNew = null; try { peNew = (ArrayList<PeoperEntity>)SerializableUtils.getSerialzable(filename); } catch (Exception e) { e.printStackTrace(); } System.out.println(peNew); }
package com.formain.lyy.service.util.serializable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializableUtils { /** * 根据文件名序列化对象并返回 * @param filename * @return Object | null * @throws Exception */ public static Object getSerialzable(String filename)throws Exception{ //创建文件输入流 FileInputStream fileInputStream = new FileInputStream(new File(filename)); //根据文件输入流获取一个对象输入流 ObjectInputStream objInputStream = new ObjectInputStream(fileInputStream); //获得对象并返回 Object obj = objInputStream.readObject(); return obj; } /** * 序列化对象 * @param seriObj * @param filename * @return * @throws Exception */ public static void serializable(Object seriObj, String filename)throws Exception{ //创建文件输出流 FileOutputStream fileOutputStream = new FileOutputStream(new File(filename)); //对象输出流对象 ObjectOutputStream objOutputStream = new ObjectOutputStream(fileOutputStream); //输出 objOutputStream.writeObject(seriObj); objOutputStream.close(); fileOutputStream.close(); } }