程序功能:编写SerializationTest.java和DeserializationTest.java程序,利用ObjectOutputStream将 student 类的实例对象信息保持到 E:\IOTest\objectSeri.dat 文件,再利用ObjectInputStream将文件中的对象信息显示出来。
时间: 2024-03-02 14:50:28 浏览: 64
好的,我理解了你的要求。下面是实现这个程序的代码:
首先是 `Student` 类的定义:
```java
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int age;
private String gender;
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
```
然后是 `SerializationTest` 类,用于将 `Student` 对象序列化并写入文件:
```java
import java.io.*;
public class SerializationTest {
public static void main(String[] args) {
Student student = new Student("张三", 18, "男");
File file = new File("E:/IOTest/objectSeri.dat");
try (OutputStream outputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
objectOutputStream.writeObject(student);
System.out.println("序列化成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
最后是 `DeserializationTest` 类,用于从文件中读取并反序列化 `Student` 对象:
```java
import java.io.*;
public class DeserializationTest {
public static void main(String[] args) {
File file = new File("E:/IOTest/objectSeri.dat");
try (InputStream inputStream = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
Object object = objectInputStream.readObject();
if (object instanceof Student) {
Student student = (Student) object;
System.out.println(student.toString());
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
注意,在序列化和反序列化过程中,要使用相同的文件和流对象,否则会导致读取失败。
希望这个程序能够满足你的需求。如果有任何问题,欢迎随时提出。
阅读全文