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 15:07:02 浏览: 128
// 创建一个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();
}
}
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![text/x-java](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)