<span style="font-size:18px;">import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
//必须继承Serializable 才能实现序列化 ,才可以传输
//ObjectOutputStream
//把一个类存放在硬盘,并通过代码读取类的信息,输出到屏幕上
class Stu implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String name;
int age;
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 Stu() {
super();
// TODO Auto-generated constructor stub
}
public Stu(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Stu [name=" + name + ", age=" + age + "]";
}
}
public class Demo8 {
public static void main(String[] args) {
Stu stu = new Stu("zhangsan", 18);
try (ObjectOutputStream oos = new ObjectOutputStream(// 从内存写入到硬盘
new FileOutputStream(new File("9988.txt")))) {// 如果不写路径,默认会建立在项目下
// 和src同级别的目录
oos.writeObject(stu);
oos.flush();
} catch (Exception e) {
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(// 从硬盘读取到内存
new File("9988.txt")))) {
Stu stu2 = (Stu) ois.readObject();
System.out.println(stu2);
} catch (Exception e) {
}
}
}
</span>
把一个类存放在硬盘,并通过代码读取类的信息,输出到屏幕上
最新推荐文章于 2021-02-27 14:18:37 发布