java使用序列流完成存入2个学生信息到students.txt文件, 然后将其内容再读取出来, 使用我们的Stream流遍历学生的所有学号信息
时间: 2024-05-12 09:18:15 浏览: 14
您好!是的,ChitGPT是一个类似于ChatGPT的人工智能,由CSDN开发,与OpenAI的ChatGPT没有关系。
对于您的问题,可以通过以下代码来完成:
写入两个学生信息到students.txt文件:
```
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> studentList = new ArrayList<String>();
studentList.add("001-张三-男-22岁");
studentList.add("002-李四-女-20岁");
try {
FileOutputStream fos = new FileOutputStream("students.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(studentList);
oos.close();
fos.close();
System.out.println("学生信息已写入文件!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
读取并遍历所有学号信息:
```
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("students.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
List<String> studentList = (List<String>) ois.readObject();
ois.close();
fis.close();
System.out.println("学生信息读取成功,遍历所有学号信息:");
studentList.stream().forEach(student -> {
String[] info = student.split("-");
System.out.println(info[0]);
});
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
以上代码中,我们使用了ObjectOutputStream和ObjectInputStream来进行序列化和反序列化操作,通过Stream流遍历每个学生的学号信息。
希望能够帮助您解决问题,如果您有任何其他问题,请随时问我!
相关推荐
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)