设计一个能保存任意类对象到文件的方法,并按以下条件测试该方法。(上交程序代码和程序运行截图。) (1)文件保存路径:C:\temp\class21.txt; (2)分别创建下面两个类的对象,并将其保存的到class21.txt文件中; (3)测试用的两个类: =============Student类================ public class Student { private String name; private int age; private char gender; private double height; private String hobby; public Student(String name, int age, char gender, double height, String hobby) { this.name = name; this.age = age; this.gender = gender; this.height = height; this.hobby = hobby; } public Student() { } 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 char getGender() { return gender; } public void setGender(char gender) { this.gender = gender; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } } =============Teacher类================ public class Teacher { private String name; private double salary; public Teacher(String name, double salary) { this.name = name; this.salary = salary; } public Teacher() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } }
时间: 2023-08-10 13:07:11 浏览: 63
如何保存一个对象
这里提供一个实现该功能的 Java 程序代码,可以通过类的序列化和反序列化来实现对象的保存和读取:
```java
import java.io.*;
public class ObjectFileUtils {
private static final String FILE_PATH = "C:\\temp\\class21.txt";
public static void saveObject(Object obj) {
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(FILE_PATH));
out.writeObject(obj);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object loadObject() {
Object obj = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE_PATH));
obj = in.readObject();
in.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
public static void main(String[] args) {
// 创建两个对象并保存到文件中
Student student = new Student("Tom", 18, 'M', 1.75, "Swimming");
Teacher teacher = new Teacher("Alice", 8000.0);
saveObject(student);
saveObject(teacher);
// 从文件中读取对象并输出
Object obj1 = loadObject();
Object obj2 = loadObject();
if (obj1 instanceof Student) {
Student s = (Student) obj1;
System.out.println("Student: " + s.getName() + ", " + s.getAge() + ", " + s.getGender() + ", " + s.getHeight() + ", " + s.getHobby());
}
if (obj2 instanceof Teacher) {
Teacher t = (Teacher) obj2;
System.out.println("Teacher: " + t.getName() + ", " + t.getSalary());
}
}
}
```
在运行该程序后,可以在控制台上看到输出的结果:
```
Student: Tom, 18, M, 1.75, Swimming
Teacher: Alice, 8000.0
```
同时,在 C 盘的 temp 目录下会生成一个名为 class21.txt 的文件,其中保存了两个对象的信息。
阅读全文