1. 程式人生 > >java中 使用輸入+輸出流對對象序列化

java中 使用輸入+輸出流對對象序列化

mage urn NPU 分享圖片 get found otf spa class

對象: 註意記得實現 Serializable

package com.nf147.sim.entity;

import java.io.Serializable;

public class News implements Serializable {
    private int id;
    private String title;
    private String body;

    public News() {
    }

    public News(int id, String title, String body) {
        this.id = id;
        
this.title = title; this.body = body; } public News(String title, String body) { this.title = title; this.body = body; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() {
return title; } public void setTitle(String title) { this.title = title; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } @Override public String toString() { return "News{" + "id=" + id + ", title=‘" + title + ‘\‘‘ + ", body=‘" + body + ‘\‘‘ + ‘}‘; } }


@Test
public void serialize() throws IOException { //對象序列化
List<News> list = Arrays.asList(
new News("yuandn", "放假了"),
new News("春節", "快來了")
);
FileOutputStream fileOutputStream = new FileOutputStream(new File("e:/news.class"));
ObjectOutputStream stream = new ObjectOutputStream(fileOutputStream);
stream.writeObject(list);
System.out.println("文件輸出完成");
stream.close();
}

@Test
public void deserialization() throws IOException, ClassNotFoundException { //對象反序列號
FileInputStream fileInputStream = new FileInputStream(new File("e:/news.class"));
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Object o = objectInputStream.readObject();
System.out.println(o);
System.out.println("文件輸入完成");
objectInputStream.close();
}
 

結果:

技術分享圖片

java中 使用輸入+輸出流對對象序列化