import java.io.*; import java.util.Arrays; import java.util.Scanner; public class FileTest { public static void main(String[] args) throws IOException, ClassNotFoundException Scanner scanner = new Scanner (System.in); String filedir = scanner. next () ; 2 String name = scanner. next () ; int age = scanner .nextInt); 1/ 请在此编写代码 ********** Begin **********/ 1/创建 Student 对象 /给对象属性赋值 1/序列化对象到文件中,并通过反序列化读取文件内容,最后打 印对象的所有属性 End
时间: 2023-08-22 21:07:02 浏览: 121
// 创建一个Student类
class Student implements Serializable {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class FileTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Scanner scanner = new Scanner(System.in);
String filedir = scanner.next();
String name = scanner.next();
int age = scanner.nextInt();
// 创建一个Student对象
Student student = new Student(name, age);
// 序列化对象到文件中
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filedir));
oos.writeObject(student);
oos.close();
// 通过反序列化读取文件内容
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filedir));
Student readStudent = (Student) ois.readObject();
// 打印对象的所有属性
System.out.println("Name: " + readStudent.getName());
System.out.println("Age: " + readStudent.getAge());
ois.close();
}
}
阅读全文