请用Java文件IO相关类读取all_score.txt中所有同学的成绩,并为每个同学在当前文件夹新建一个独立的txt文件(以同学姓名作为文件名),并把每个同学的成绩信息写入自己专属的txt文件中。
时间: 2024-06-15 07:08:11 浏览: 6
在Java中,可以使用File类和FileReader类来读取文件内容,使用FileWriter类来写入文件内容。下面是一个示例代码,演示如何读取all_score.txt文件中的成绩信息,并将每个同学的成绩写入以同学姓名为文件名的txt文件中:
```java
import java.io.*;
public class FileIOExample {
public static void main(String[] args) {
try {
// 读取all_score.txt文件
File inputFile = new File("all_score.txt");
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
// 解析每行数据,假设格式为"姓名 成绩"
String[] data = line.split(" ");
String name = data[0];
int score = Integer.parseInt(data[1]);
// 创建同学姓名对应的txt文件
File outputFile = new File(name + ".txt");
FileWriter fileWriter = new FileWriter(outputFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
// 将成绩信息写入txt文件
bufferedWriter.write("姓名:" + name);
bufferedWriter.newLine();
bufferedWriter.write("成绩:" + score);
bufferedWriter.close();
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请注意,以上代码仅为示例,实际使用时需要根据具体情况进行适当修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)