class CashCheck implements Serializable { private static final long serialVersionUID = -8872155900725314694L;
private String cashCheckID;
private int cashAmout;
public CashCheck() { }
public String getCashCheckID() { return cashCheckID; }
public void setCashCheckID(String cashCheckID) { this.cashCheckID = cashCheckID; }
public int getCashAmout() { return cashAmout; }
public void setCashAmout(int cashAmout) { this.cashAmout = cashAmout; } }
public class SerializeDemo01 { public static void main(String[] args) { CashCheck check = new CashCheck(); check.setCashAmout(10000); check.setCashCheckID("notifier");
/* * 序列化对象 */ try { // 1.创建文件输出流,负责将字节写入文件 FileOutputStream fs = new FileOutputStream( new File( "C:\\Documents and Settings\\Administrator\\桌面\\notifier.file"));
// 2.创建对象输出流,负责将对象转为字节 ObjectOutputStream os = new ObjectOutputStream(fs);
// 3.写入对象 os.writeObject(check);
// 4.关闭对象输出流 os.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
/* * 解序列化对象 */ try { // 1.创建文件输入流,负责将文件转为字节 FileInputStream fi = new FileInputStream( "C:\\Documents and Settings\\Administrator\\桌面\\notifier.file");
// 2.创建对象输入流,负责将字节写入对象 ObjectInputStream oi = new ObjectInputStream(fi);
// 3.读出对象 Object o1 = oi.readObject(); if (o1 instanceof CashCheck) { CashCheck check1 = (CashCheck) o1; System.out.println(check1.getCashCheckID()); System.out.println(check1.getCashAmout()); }
// 4.关闭对象输入流 oi.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }
/* * 以文件的形式读出序列化文件,是乱码 */ try { FileReader fr = new FileReader( new File( "C:\\Documents and Settings\\Administrator\\桌面\\notifier.file")); BufferedReader br = new BufferedReader(fr);
String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |