java读取文件转换成对象
时间: 2023-09-22 15:12:00 浏览: 56
步骤如下:
1. 定义一个类,表示需要读取的对象,该类需要实现 Serializable 接口。
2. 创建一个 FileInputStream 对象,读取文件。
3. 创建一个 ObjectInputStream 对象,用于将读取的文件转换成对象。
4. 使用 ObjectInputStream 的 readObject() 方法,将文件转换成对象。
5. 关闭 FileInputStream 和 ObjectInputStream 对象。
示例代码:
```java
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class ReadObjectFromFile {
public static void main(String[] args) {
try {
// 1. 定义需要读取的对象类
class Person implements java.io.Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
// 2. 创建 FileInputStream 对象,读取文件
FileInputStream fileIn = new FileInputStream("person.ser");
// 3. 创建 ObjectInputStream 对象,将文件转换成对象
ObjectInputStream in = new ObjectInputStream(fileIn);
// 4. 将文件转换成对象
Person person = (Person) in.readObject();
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
// 5. 关闭 FileInputStream 和 ObjectInputStream 对象
in.close();
fileIn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
注意事项:
1. 需要读取的对象类必须实现 Serializable 接口。
2. FileInputStream 和 ObjectInputStream 对象都需要关闭。
3. 如果读取的文件不是需要读取的对象类,将会抛出 ClassCastException 异常。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)