java:需求:读取文件中的数据 33 22 11 55 44 排序后 11 22 33 44 55 再次写到本地文件
以下是一个Java程序,可以实现读取文件中的数据,排序后再次写到本地文件的需求:
import java.io.*;
import java.util.*;
public class FileSorter {
public static void main(String[] args) {
// 定义文件路径
String filePath = "data.txt";
// 读取文件中的数据
List<Integer> dataList = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
String[] nums = line.split(" ");
for (String num : nums) {
dataList.add(Integer.parseInt(num));
}
}
} catch (IOException e) {
e.printStackTrace();
return;
}
// 对数据进行排序
Collections.sort(dataList);
// 将排序后的数据写入文件
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
for (int num : dataList) {
writer.write(num + " ");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上程序逻辑如下:
- 定义文件路径
filePath为data.txt。 - 读取文件中的数据,定义一个
dataList列表,使用BufferedReader读取文件数据,并将每行数据按空格分割后转为整型加入dataList中。 - 对
dataList列表进行排序,使用Collections.sort方法。 - 将排序后的数据写入文件,使用
BufferedWriter将每个整型数值转为字符串后写入文件中。
程序运行后,data.txt 中的数据将被排序后再次写入
原文地址: https://www.cveoy.top/t/topic/fGbv 著作权归作者所有。请勿转载和采集!