/*3.(文件)编写一个程序,检测本地是否保存学生对象(反序列化,D:\student.txt), 如果保存,则输出学生的信息;如果没有保存, 则通过学生类Student(Name, Age, Hobby)创建一个学生对象,将学生信息输出到控制台并保存到该文件中(序列化)中。
时间: 2023-12-03 18:45:09 浏览: 57
以下是一个示例代码实现:
```java
import java.io.*;
public class StudentTest {
public static void main(String[] args) {
String filePath = "D:\\student.txt";
Student student = null;
try {
FileInputStream fileIn = new FileInputStream(filePath);
ObjectInputStream in = new ObjectInputStream(fileIn);
student = (Student) in.readObject();
in.close();
fileIn.close();
System.out.println("从文件中读取学生信息:");
System.out.println(student.toString());
} catch (IOException | ClassNotFoundException e) {
System.out.println("未找到保存的学生信息,创建新的学生对象并保存。");
student = new Student("张三", 18, "篮球");
try {
FileOutputStream fileOut = new FileOutputStream(filePath);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(student);
out.close();
fileOut.close();
System.out.println("学生信息已保存到文件中。");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
class Student implements Serializable {
private String name;
private int age;
private String hobby;
public Student(String name, int age, String hobby) {
this.name = name;
this.age = age;
this.hobby = hobby;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getHobby() {
return hobby;
}
@Override
public String toString() {
return "姓名:" + name + ",年龄:" + age + ",爱好:" + hobby;
}
}
```
这个程序会首先尝试从指定文件中读取学生对象,如果读取成功,就输出学生的信息;如果读取失败,就创建一个新的学生对象,并将其保存到文件中。在这个示例代码中,我们使用了 Java 的序列化和反序列化机制来实现学生对象的保存和读取。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)