Java对象文件动态演示
时间: 2024-03-05 08:50:19 浏览: 14
很抱歉,我是一个文本AI助手,无法进行动态演示。但我可以给你提供一些参考。
Java对象文件可以通过序列化和反序列化来实现对象的文件存储和读取。下面是一个简单的示例代码:
```java
import java.io.*;
public class ObjectFileDemo {
public static void main(String[] args) {
// 创建对象
Student student = new Student("张三", 18, "计算机科学");
// 序列化对象到文件
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.obj"))) {
oos.writeObject(student);
System.out.println("对象序列化成功!");
} catch (IOException e) {
e.printStackTrace();
}
// 从文件反序列化对象
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.obj"))) {
Student s = (Student) ois.readObject();
System.out.println(s);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Student implements Serializable {
private String name;
private int age;
private String major;
public Student(String name, int age, String major) {
this.name = name;
this.age = age;
this.major = major;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", major='" + major + '\'' +
'}';
}
}
```
在这个示例中,我们创建了一个`Student`对象,并将其序列化到`student.obj`文件中。然后,我们从文件中读取对象,并将其转换为`Student`类型进行输出。
需要注意的是,被序列化的对象必须实现`Serializable`接口,否则会抛出`NotSerializableException`异常。在序列化和反序列化时,需要使用`ObjectOutputStream`和`ObjectInputStream`来进行操作。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)