//注意对象类要打标记实现Serializable接口
1 package com.gh; 2 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.io.ObjectInputStream; 9 import java.io.ObjectOutputStream; 10 import java.io.OutputStream; 11 12 public class ObjectStreamDemo { 13 /** 14 * 对象序列化 15 * 把对象写入到文件中 16 */ 17 public static void writeobject(){ 18 try { 19 OutputStream out =new FileOutputStream("1.gh"); 20 ObjectOutputStream oos=new ObjectOutputStream(out); 21 Person p=new Person("小白", 8); 22 oos.writeObject(p); 23 oos.close(); 24 } catch (FileNotFoundException e) { 25 e.printStackTrace(); 26 } catch (IOException e) { 27 e.printStackTrace(); 28 } 29 } 30 /** 31 * 对象的反序列化, 32 * 从文件中读取对象 33 */ 34 public static void readobject(){ 35 try { 36 InputStream in=new FileInputStream("1.gh"); 37 ObjectInputStream ois=new ObjectInputStream(in); 38 Person ps=(Person)ois.readObject(); 39 in.close(); 40 System.out.println(ps); 41 } catch (FileNotFoundException e) { 42 e.printStackTrace(); 43 } catch (IOException e) { 44 e.printStackTrace(); 45 } catch (ClassNotFoundException e) { 46 e.printStackTrace(); 47 } 48 } 49 public static void main(String[] args) { 50 //writeobject(); 51 readobject(); 52 } 53 }
1 package com.gh; 2 3 import java.io.Serializable; 4 5 public class Person implements Serializable{//标记可以序列化 6 private String name; 7 private int age; 8 public String getName() { 9 return name; 10 } 11 public void setName(String name) { 12 this.name = name; 13 } 14 public int getAge() { 15 return age; 16 } 17 public void setAge(int age) { 18 this.age = age; 19 } 20 public Person() { 21 super(); 22 } 23 public Person(String name, int age) { 24 this.name = name; 25 this.age = age; 26 } 27 @Override 28 public String toString() { 29 return "Person [name=" + name + ", age=" + age + "]"; 30 } 31 32 }
时间: 2024-10-22 05:46:03