序例化多個對象
阿新 • • 發佈:2017-06-05
() put args 多個 stat println clas 一個 數組參數
package serializable.cn; import java.io.Serializable; /* * 多個對象序例化 */ public class Person implements Serializable { private String name; private int age; public Person(String name,int age){ this.age = age; this.name = name; } public String toString (){return "姓名:"+this.name+",年齡:"+this.age; } }
package serializable.cn; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; public class SerializableDemo {public static void main(String[] args) throws Throwable { //new 多個對象出來 Person [] per = {new Person("張三",30),new Person("李四",40),new Person("王五",50)}; //ser()接收的是數組類型的參數 ser(per); //dser()返回的是一個數組 Object[] ct = dser(); //遍歷數組 for (int i = 0; i < ct.length; i++) {// 方法 1:System.out.println(ct[i]); //方法2 :將數組內容 轉換為person對象 Person p = (Person)ct[i]; System.out.println(p); } } //序例化類,傳一個object類型的數組參數 public static void ser(Object[] obj) throws Throwable{ File f = new File("d:"+File.separator+"e.txt"); OutputStream out = new FileOutputStream(f); ObjectOutputStream otp = new ObjectOutputStream(out); //void writeObject(Object obj) 將指定的對象寫入 ObjectOutputStream。 otp.writeObject(obj); otp.close(); } //反序例化類,返回一個object 數組 public static Object[] dser() throws Throwable{ File f = new File("d:"+File.separator+"e.txt"); InputStream ip = new FileInputStream(f); //new 一個對象輸入流 ObjectInputStream oji = new ObjectInputStream(ip); Object[] jec = ( Object[])oji.readObject(); oji.close(); return jec; } }
序例化多個對象