第一讲 对象序列化(持久化)
一、概述:就是把对象封存在硬盘,可以保持数据;关键类:ObjectInputStream和ObjectOutpurStream
二、
关键字:ObjectOutputStream:方法有writerObject()读取 ObjectInputStream 方法有readObject() 被序列化的对象需要 implements Serializable关于被序列化的类需要实现Serializable它等于一个撮,标识用的,改变类里面的语句就变了。如果想固定一个撮,可以:
public static final long serialVersionUId=42L;//给他固定一个撮1、写入流对象 使用writerObject(Object obj)方法,将对象作为参数传入2、读取流对象 适应readObject(Object obj)方法,方法注:被static和transient修饰后不能被序列化保存
1 /*一下主要为了演示如何对象序列化 2 * 关键字:ObjectOutputStream:方法有writerObject()读取 3 * ObjectInputStream 方法有readObject() 4 * 被序列化的对象需要 implements Serializable 5 * 6 */ 7 import java.io.*; 8 public class ObjectStreamDemo { 9 public static void main(String[] args) throws IOException,ClassNotFoundException{ 10 11 Person p=new Person("水音",25,"kr"); 12 13 File f=new File("D:\\sy.txt"); 14 15 writeObj(p,f); 16 readObj(f); 17 } 18 19 private static void writeObj(Person p, File f) { 20 ObjectOutputStream oos=null; 21 try { 22 oos=new ObjectOutputStream(new FileOutputStream(f)); 23 oos.writeObject(p); 24 } catch (IOException e) { 25 throw new RuntimeException("对象写入失败"); 26 } 27 finally{ 28 try { 29 if(oos!=null) 30 oos.close(); 31 } catch (Exception e2) { 32 throw new RuntimeException("关流失败"); 33 } 34 } 35 } 36 //读取 37 private static void readObj(File f) { 38 ObjectInputStream ois=null; 39 try { 40 ois=new ObjectInputStream(new FileInputStream(f)); 41 Person p=(Person)ois.readObject(); 42 System.out.println(p); 43 } catch (Exception e) { 44 // TODO: handle exception 45 } 46 finally{ 47 try { 48 if(ois!=null) 49 ois.close(); 50 } catch (Exception e3) { 51 throw new RuntimeException("关流失败"); 52 } 53 } 54 55 } 56 // 视频读取 57 public static void readObj()throws IOException, ClassNotFoundException{ 58 ObjectInputStream ois= 59 new ObjectInputStream(new FileInputStream("D:\\sy.txt")); 60 Person p=(Person)ois.readObject(); 61 System.out.println(p); 62 ois.close(); 63 } 64 65 // 视频方法存储 66 public static void writeObj()throws IOException{ 67 68 ObjectOutputStream oos= 69 new ObjectOutputStream(new FileOutputStream("D:\\sy.txt")); 70 oos.writeObject(new Person("水音",24,"kr")); 71 oos.writeObject(new Person("水音",25)); 72 oos.close(); 73 } 74 } 75 76 //创建类 77 class Person implements Serializable{//必须实现这个才能被序列化 78 public static final long serialVersionUId=42L;//给他固定一个撮 79 80 private String name; 81 transient int age;//使用transient后就不能被序列化 82 static String country="cn";//静态也不能序列化 83 Person(String name,int age,String country){ 84 this.name=name; 85 this.age=age; 86 this.country=country; 87 } 88 public String toString(){ 89 return name+"="+age+"="+country; 90 } 91 }
时间: 2024-11-18 22:53:36