进阶day10-.序列化流保存对象(ObjectOutputStream)
This commit is contained in:
29
javaSE-day10/src/com/inmind/object_stream03/Demo11.java
Normal file
29
javaSE-day10/src/com/inmind/object_stream03/Demo11.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package com.inmind.object_stream03;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectOutputStream;
|
||||
|
||||
/*
|
||||
序列化流对象(ObjectOutputStream)
|
||||
|
||||
构造方法:
|
||||
ObjectOutputStream(OutputStream out) 创建一个写入指定的OutputStream的ObjectOutputStream。
|
||||
|
||||
常用方法:
|
||||
void writeObject(Object obj) 将指定的对象写入ObjectOutputStream。
|
||||
|
||||
注意:要进行序列化,被序列化的对象类必须实现一个接口Serializable,否则会报NotSerializableException
|
||||
*/
|
||||
public class Demo11 {
|
||||
public static void main(String[] args) throws IOException {
|
||||
Student s = new Student("张三", 20);
|
||||
|
||||
//序列化:将java对象保存到文件中
|
||||
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.txt"));
|
||||
oos.writeObject(s);
|
||||
|
||||
oos.close();
|
||||
}
|
||||
}
|
||||
15
javaSE-day10/src/com/inmind/object_stream03/Student.java
Normal file
15
javaSE-day10/src/com/inmind/object_stream03/Student.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.inmind.object_stream03;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user