try { ObjectInputStream ois=new ObjectInputStream(new FileInputStream("D:\\studentdatabase.dat")); List<student> inputlist=new ArrayList<>(); inputlist=(List<student>)ois.readObject(); for(student st:inputlist) { System.out.println(st); } ois.close(); }catch(ClassNotFoundException e) {}
时间: 2024-03-14 19:49:21 浏览: 32
这段代码是Java中读取对象序列化数据并将其反序列化为对象列表的代码。它首先创建一个ObjectInputStream对象,然后使用它来读取一个以前序列化的对象列表,将其转换为List<student>类型,并将其存储在inputlist变量中。然后,它遍历该列表并将每个学生对象打印出来。最后,它关闭ObjectInputStream对象。
需要注意的是,如果在反序列化对象时没有找到相应的类,则会抛出ClassNotFoundException异常。在这种情况下,该异常被捕获但不会被处理,因为这个代码块中没有任何处理它的代码。
相关问题
ObjectInputStream ois = new ObjectInputStream( new FileInputStream(file) );
这段代码是用来从文件中读取对象的。首先通过`FileInputStream`打开指定的文件,然后通过`ObjectInputStream`读取文件中的对象。这些对象必须是之前使用`ObjectOutputStream`写入文件的,而且读取的顺序必须与写入的顺序相同。如果读取的对象类型与写入的对象类型不同,程序可能会抛出`ClassCastException`异常。读取完毕后,关闭文件流以释放资源。
oo = new ObjectInputStream(new FileInputStream("d:/cheliang.txt"));
这段代码使用了 Java 标准库中的 ObjectInputStream 类和 FileInputStream 类,目的是从指定路径 "d:/cheliang.txt" 读取一个序列化的 Java 对象。
具体来说,这段代码的作用是:
1. 创建一个 FileInputStream 对象,用于读取指定路径下的文件。
2. 创建一个 ObjectInputStream 对象,用于从 FileInputStream 中读取序列化的 Java 对象。
3. 使用 readObject() 方法读取 Java 对象,返回的是 Object 类型,需要进行类型转换。
4. 关闭 ObjectInputStream 和 FileInputStream。
以下是一个示例代码:
```
import java.io.*;
public class ReadObject {
public static void main(String[] args) {
try {
// 创建 ObjectInputStream 和 FileInputStream
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/cheliang.txt"));
// 读取 Java 对象
Object obj = ois.readObject();
Car car = (Car)obj;
// 输出对象内容
System.out.println("Brand: " + car.getBrand());
System.out.println("Model: " + car.getModel());
System.out.println("Year: " + car.getYear());
// 关闭 ObjectInputStream 和 FileInputStream
ois.close();
} catch(IOException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
这段代码会从 "d:/cheliang.txt" 中读取一个 Car 对象,并输出对象的品牌、型号和年份。你可以根据自己的需求修改读取的文件路径和读取的对象类型。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)