溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java使用Serializable接口實現(xiàn)序列化的方法

發(fā)布時間:2020-05-20 16:23:28 來源:億速云 閱讀:192 作者:鴿子 欄目:編程語言

Serializable接口是一個標記接口,不用實現(xiàn)任何方法,一旦某個類實現(xiàn)了該方法,則該類的對象是可序列化的。

具體步驟:

1、創(chuàng)建一個ObjectOutputStream輸出流;

2、調用OjectOutputSteam對象的writeObject ()輸出可序列化對象。

public class Person implements Serializable {
	private String name;
	private String age;

	public Person() {
		System.out.println("調用Person的無參構造函數(shù)");
	}

	public Person(String name, String age) {
		this.name = name;
		this.age = age;
		System.out.println("調用Person的有參構造函數(shù)");
	}

	@Override
	public String toString() {
		// TODO 自動生成的方法存根
		return "Person{'name' :" + name + ",'age' :" + age + "}";
	}
}
public class WriteObject {
	public static void main(String[] args) {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Person.txt"));
			Person p = new Person("baby", "12");
			oos.writeObject(p);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

輸出如下:

aced 0005 7372 0017 7365 7269 616c 697a
6162 6c65 5465 7374 2e50 6572 736f 6e4e
aff9 165f 38dd f602 0002 4c00 0361 6765
7400 124c 6a61 7661 2f6c 616e 672f 5374
7269 6e67 3b4c 0004 6e61 6d65 7100 7e00
0178 7074 0002 3132 7400 0462 6162 79

以上就是java中如何使用Serializable接口實現(xiàn)序列化的詳細內容,更多請關注億速云其它相關文章!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI