Demo01.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package J20250728.homework;
  2. import java.io.*;
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. /**
  6. * @author WanJl
  7. * @version 1.0
  8. * @title Demo01
  9. * @description
  10. * @create 2025/7/28
  11. */
  12. public class Demo01 {
  13. /**
  14. * ## 作业1:
  15. *
  16. * - 使用字符缓冲流读取文件中的数据,排序后再次写到本地文件
  17. * - 实现步骤
  18. * - 将文件中的数据读取到程序中
  19. * - 对读取到的数据进行处理
  20. * - 将处理后的数据添加到集合中
  21. * - 对集合中的数据进行排序
  22. * - 将排序后的集合中的数据写入到文件中
  23. * @param file
  24. */
  25. public static void textSort(String file) throws IOException {
  26. //1、创建字符输入流和处理流
  27. FileReader fr=new FileReader(file);
  28. BufferedReader br=new BufferedReader(fr);
  29. //创建接收整数的集合,循环读取一行一行的整数,转换为Int类型,并存入集合
  30. String t;
  31. ArrayList<Integer> arrayList=new ArrayList<>();
  32. while ((t= br.readLine())!=null){
  33. int i = Integer.parseInt(t);
  34. arrayList.add(i);
  35. }
  36. //排序
  37. arrayList.sort(Integer::compareTo);
  38. //创建字符输出流和处理流
  39. FileWriter fw=new FileWriter(file);
  40. BufferedWriter bw=new BufferedWriter(fw);
  41. //循环存数字的集合,在集合中获取每个元素并转换为字符串,并且写入到文件中,每写一个元素就换行一次
  42. for (int i = 0; i < arrayList.size(); i++) {
  43. String s = arrayList.get(i) + "";
  44. bw.write(s);
  45. bw.newLine();
  46. }
  47. //关闭流
  48. br.close();
  49. bw.close();
  50. fr.close();
  51. fw.close();
  52. }
  53. public static void main(String[] args) throws IOException {
  54. textSort("D:/排序.txt");
  55. }
  56. }