Java學習筆記——序列化和還原序列化

來源:互聯網
上載者:User

標籤:static   name   bin   span   warning   讀取   異常   檔案   swa   

 

寒雨連江夜入吳,平明送客楚山孤。

洛陽親友如相問,一片冰心在玉壺。

              ——芙蓉樓送辛漸

持久化資料的第一種方式。在序列化之前也可以把資料打散逐行儲存在檔案中,然後在逐行讀取。

比如定Student類

用字元輸出資料流把Student類的所有屬性存入本地檔案:

張三|18|男

李四|18|女

讀取一行,用|分隔的資料分別為學生的name,age,gender,建立學生對象並加入學生集合

迴圈上一步直到br.readLine = null

至於這種方法怎麼儲存物件的其他資訊那就不清楚了。

下面來看序列化

上代碼:

 1 public class SerializableDemo { 2  3     public static void main(String[] args) throws IOException, ClassNotFoundException { 4         //序列化對象obj,將obj存入本地檔案obj.bin.對象obj的類必須Serializable介面 5         OutputStream os = new FileOutputStream("/home/yanshaochen/public/obj.bin");//OutputStream抽象類別 6         ObjectOutputStream oos = new ObjectOutputStream(os);//ObjectOutputStream執行個體類 7         oos.writeObject(obj);//持久化obj 8         oos.close(); 9         //還原序列化10         InputStream is = new FileInputStream("/home/yanshaochen/public/obj.bin");11         ObjectInputStream ois = new ObjectInputStream(is);12         @SuppressWarnings("unchecked")13         Object obj =(Object)ois.readObject();//強制轉換可能出現ClassNotFoundException異常14     }15 }

 

Java學習筆記——序列化和還原序列化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.