2018-07-25期 Java序列化和還原序列化編程小案例

來源:互聯網
上載者:User

標籤:system   cep   序列化   new   []   java序列化   except   temp   port   

package cn.sjq.Serializable.java;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.OutputStream;

/**

* 將Fruit對象寫入檔案

* @author songjq

*

*/

public class JavaSerializableDemo {

public static void main(String[] args) throws Exception {

//定義水果對象

Fruit f = new Fruit();

f.setName("Apple");

f.setType("001");

f.setProduction("China");

/*

* 將水果對象f寫入檔案(Fruit未實現序列化)

*/

//定義輸出資料流

OutputStream out = new FileOutputStream("d:\\temp\\Fruit.ser");

//定義對象輸出資料流

ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);

objectOutputStream.writeObject(f);

//關閉流

out.close();

objectOutputStream.close();

/**

* 測試結論:

* 1、Fruit未實現序列化

* Exception in thread "main" java.io.NotSerializableException: cn.sjq.Serializable.java.Fruit

* 說明如果一個對象要被寫入檔案,需要對該對象進行序列化

* 2、Fruit實現序列化 public class Fruit implements Serializable

* 對象Fruit成功寫入了檔案d:\\temp\\Fruit.ser

*/

/**

* 還原序列化,將Fruit.ser還原序列化成Fruit對象輸出控制台

*/

InputStream in = new FileInputStream("d:\\temp\\Fruit.ser");

ObjectInputStream objectInputStream = new ObjectInputStream(in);

Fruit fruit = (Fruit) objectInputStream.readObject();

System.out.println(f.getName()+"\t"+f.getType()+"\t"+f.getProduction());

/*

* 輸出結果:

* Apple001China

*/

}

}

package cn.sjq.Serializable.java;

import java.io.Serializable;

/**

* Java序列化:如果一個類實現了Java序列化,這個類就可以作為輸入輸出對象

* 定義一個JAVA Bean Fruit

* @author songjq

*

*/

public class Fruit implements Serializable {

private String name;

private String type;

private String production;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getType() {

return type;

}

public void setType(String type) {

this.type = type;

}

public String getProduction() {

return production;

}

public void setProduction(String production) {

this.production = production;

}

}


2018-07-25期 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.