123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- package J20250728.homework;
- import java.io.*;
- import java.util.ArrayList;
- import java.util.Arrays;
- /**
- * @author WanJl
- * @version 1.0
- * @title Demo01
- * @description
- * @create 2025/7/28
- */
- public class Demo01 {
- /**
- * ## 作业1:
- *
- * - 使用字符缓冲流读取文件中的数据,排序后再次写到本地文件
- * - 实现步骤
- * - 将文件中的数据读取到程序中
- * - 对读取到的数据进行处理
- * - 将处理后的数据添加到集合中
- * - 对集合中的数据进行排序
- * - 将排序后的集合中的数据写入到文件中
- * @param file
- */
- public static void textSort(String file) throws IOException {
- //1、创建字符输入流和处理流
- FileReader fr=new FileReader(file);
- BufferedReader br=new BufferedReader(fr);
- //创建接收整数的集合,循环读取一行一行的整数,转换为Int类型,并存入集合
- String t;
- ArrayList<Integer> arrayList=new ArrayList<>();
- while ((t= br.readLine())!=null){
- int i = Integer.parseInt(t);
- arrayList.add(i);
- }
- //排序
- arrayList.sort(Integer::compareTo);
- //创建字符输出流和处理流
- FileWriter fw=new FileWriter(file);
- BufferedWriter bw=new BufferedWriter(fw);
- //循环存数字的集合,在集合中获取每个元素并转换为字符串,并且写入到文件中,每写一个元素就换行一次
- for (int i = 0; i < arrayList.size(); i++) {
- String s = arrayList.get(i) + "";
- bw.write(s);
- bw.newLine();
- }
- //关闭流
- br.close();
- bw.close();
- fr.close();
- fw.close();
- }
- public static void main(String[] args) throws IOException {
- textSort("D:/排序.txt");
- }
- }
|