s-day10--序列化流保存对象(ObjectOutputStream)
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
package com.inmind.xlh03;
|
||||
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
|
||||
/*
|
||||
14.序列化流保存对象(ObjectOutputStream)
|
||||
构造方法:
|
||||
ObjectOutputStream(OutputStream out) 创建一个写入指定的OutputStream的ObjectOutputStream。
|
||||
常用方法:
|
||||
void writeObject(Object obj) 将指定的对象写入ObjectOutputStream。
|
||||
*/
|
||||
public class Demo08 {
|
||||
public static void main(String[] args) throws Exception{
|
||||
//创建一个学生对象
|
||||
Student s = new Student("张三", 18);
|
||||
//创建序列化流对象
|
||||
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.txt"));
|
||||
//将对象写出到文件中
|
||||
oos.writeObject(s);
|
||||
oos.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.inmind.xlh03;
|
||||
|
||||
import java.io.Serializable;
|
||||
//Serializable:该接口是允许序列化的接口
|
||||
public class Student implements Serializable {
|
||||
String name;
|
||||
int age;
|
||||
|
||||
public Student(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Student{" +
|
||||
"name='" + name + '\'' +
|
||||
", age=" + age +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user