1. 程式人生 > >輸入輸出流-序列化和反序列化

輸入輸出流-序列化和反序列化

 1 package demo;
 2 
 3 import java.io.Serializable;
 4 
 5 public class Student implements Serializable{
 6     private String name;  //姓名
 7     private int id;  //學號
 8     private String sex;  //性別
 9     
10     public Student() {
11     }
12 
13     public Student(String name, int id, String sex) {
14
this.name = name; 15 this.id = id; 16 this.sex = sex; 17 } 18 19 public String getName() { 20 return name; 21 } 22 23 public void setName(String name) { 24 this.name = name; 25 } 26 27 public int getId() { 28 return id; 29 }
30 31 public void setId(int id) { 32 this.id = id; 33 } 34 35 public String getSex() { 36 return sex; 37 } 38 39 public void setSex(String sex) { 40 this.sex = sex; 41 } 42 43 44 }
 1 package demo;
 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.ObjectInputStream; 8 import java.io.ObjectOutputStream; 9 import java.util.ArrayList; 10 11 public class Test8 { 12 //序列化 13 public static void objectOutput(String path) { 14 ObjectOutputStream oos=null; 15 FileOutputStream fos=null; 16 17 try { 18 fos=new FileOutputStream(path); 19 oos=new ObjectOutputStream(fos); 20 Student stu1=new Student("李明",01,"男"); 21 Student stu2=new Student("張晴",02,"女"); 22 Student stu3=new Student("吳勇",03,"男"); 23 ArrayList<Student> list=new ArrayList(); 24 list.add(stu1); 25 list.add(stu2); 26 list.add(stu3); 27 //物件序列化,寫入輸出流 28 oos.writeObject(list); 29 } catch (FileNotFoundException e) { 30 e.printStackTrace(); 31 } catch (IOException e) { 32 e.printStackTrace(); 33 }finally { 34 try { 35 if(oos!=null) { 36 oos.close(); 37 } 38 if(fos!=null) { 39 fos.close(); 40 } 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } 44 } 45 } 46 47 //反序列化 48 public static void objectInput(String path) { 49 ObjectInputStream ois=null; 50 FileInputStream fis=null; 51 52 try { 53 fis=new FileInputStream(path); 54 ois=new ObjectInputStream(fis); 55 //反序列化,進行強轉型別轉換 56 ArrayList<Student> list=(ArrayList<Student>)ois.readObject(); 57 //輸出生成後的物件資訊 58 for (Student stu : list) { 59 System.out.println("姓名是:"+stu.getName()+"\n學號是:"+stu.getId()+"\n性別是:"+stu.getSex()); 60 } 61 } catch (FileNotFoundException e) { 62 e.printStackTrace(); 63 } catch (IOException e) { 64 e.printStackTrace(); 65 } catch (ClassNotFoundException e) { 66 e.printStackTrace(); 67 }finally { 68 69 } 70 71 } 72 73 public static void main(String[] args) { 74 objectOutput("test2.txt"); 75 objectInput("test2.txt"); 76 } 77 }