java练习-读取写入文件、数组排序
需求:
/*
文本文件中有以下的数据:
2-1-9-4-7-8
将文件中的数据进行排序,变成以下的数据:
1-2-4-7-8-9
*/
package com.example.ss_0203_array.test.test_0901; import java.io.*; import java.util.*; import java.util.stream.Stream; public class test1 { public static void main(String[] args) { File file = new File("F:\\阿里云盘下载\\Java入门到起飞-2\\day28-IO(字节流&字符流)\\代码\\AAA.txt"); try { FileReader fr = new FileReader("F:\\阿里云盘下载\\Java入门到起飞-2\\day28-IO(字节流&字符流)\\代码\\AAA.txt"); StringBuilder str = new StringBuilder(); int ch; while ((ch = fr.read()) != -1) { str.append((char) ch); } String s = str.toString(); String[] arrStr = s.split("-"); ArrayList<Integer> list = new ArrayList<>(); for (String s1 : arrStr) { list.add(Integer.parseInt(s1)); } Collections.sort(list); FileWriter fw = new FileWriter("F:\\阿里云盘下载\\Java入门到起飞-2\\day28-IO(字节流&字符流)\\代码\\AAA.txt"); for (int i = 0; i < list.size(); i++) { if (i == list.size() - 1) { fw.write(list.get(i) + ""); } else { fw.write(list.get(i) + "-"); } } fw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
实现方式2:
package com.example.ss_0203_array.test.test_0901; import java.io.*; import java.util.*; import java.util.stream.Stream; public class test1 { public static void main(String[] args) { File file = new File("F:\\阿里云盘下载\\Java入门到起飞-2\\day28-IO(字节流&字符流)\\代码\\AAA.txt"); try { FileReader fr = new FileReader("F:\\阿里云盘下载\\Java入门到起飞-2\\day28-IO(字节流&字符流)\\代码\\AAA.txt"); StringBuilder str = new StringBuilder(); int ch; while ((ch = fr.read()) != -1) { str.append((char) ch); } fr.close(); Integer[] arr = Arrays.stream(str.toString().split("-")) .map(Integer::parseInt) .sorted() .toArray(Integer[]::new); FileWriter fw = new FileWriter("F:\\阿里云盘下载\\Java入门到起飞-2\\day28-IO(字节流&字符流)\\代码\\AAA.txt"); String arrstr = Arrays.toString(arr).replace(", ","-").replace("[","").replace("]",""); fw.write(arrstr); fw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }