java list转文件流
时间: 2023-10-11 17:04:30 浏览: 49
Java中的List可以通过Java IO库中的ObjectOutputStream类进行转换为文件流。以下是一个示例代码:
```java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ListToFileStream {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
try {
FileOutputStream fileOut = new FileOutputStream("list.txt");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(list);
objectOut.close();
fileOut.close();
System.out.println("List saved to file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,首先创建了一个List对象,并添加了一些元素。然后创建了一个FileOutputStream对象和一个ObjectOutputStream对象,用于将List对象写入文件。最后关闭了输出流。
可以使用以下代码将文件流转换回List对象:
```java
import java.io.*;
import java.util.List;
public class FileStreamToList {
public static void main(String[] args) {
try {
FileInputStream fileIn = new FileInputStream("list.txt");
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
List<String> list = (List<String>) objectIn.readObject();
objectIn.close();
fileIn.close();
System.out.println("List read from file:");
for (String item : list) {
System.out.println(item);
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,首先创建了一个FileInputStream对象和一个ObjectInputStream对象,用于读取包含List对象的文件。然后从文件中读取List对象,并关闭输入流。最后打印了读取的List对象的元素。
相关推荐
![](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)