码迷,mamicode.com
首页 > 其他好文 > 详细

对象流

时间:2019-11-10 19:10:37      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:turn   super   接口   pack   this   txt   关闭   cep   name   

写对象:序列化,对象的状态以字节的形式储存

读对象:反序列化,磁盘上的字节形式的数据还原成对象的内存状态

只有实现了serializable接口才可以被序列化

package com.study02;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


public class a04 {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
write();
read();
}

public static void read() throws FileNotFoundException, IOException, ClassNotFoundException {
//创建流
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("g.txt"));
//写对象
System.out.println(ois.readObject());
//关闭
ois.close();

}


public static void write() throws FileNotFoundException, IOException {
//创建对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("g.txt"));
//写对象
oos.writeObject(new person("陆俊龙",20));

//关闭
if (oos!=null) {
oos.close();
}
}

}

 

package com.study02;

import java.io.Serializable;

public class person implements Serializable{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public person(String name, int age) {
super();
this.name = name;
this.age = age;
}
private int age;
@Override
public String toString() {
return name;
}
}

对象流

标签:turn   super   接口   pack   this   txt   关闭   cep   name   

原文地址:https://www.cnblogs.com/LuJunlong/p/11831182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!