Java-->把txt中的所有字符按照码表值排序
--> List 列表中的自动添加的多余空间长度该怎么去除呢?...(已解决,是char 数组中的空字符)
package com.dragon.java.filesort; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /* * 将day19-笔记.txt中的所有字符按照码表值排序, 存入另一个文件中 */ public class Test { public static void main(String args[]) { FileReader fr = null; FileWriter fw = null; ArrayList<Character> list = new ArrayList<>(); try { fr = new FileReader( "C:/Users/xy/Desktop/文件/Java/Java/DailyCode/08-14/src/com/dragon/java/days.txt"); fw = new FileWriter( "C:/Users/xy/Desktop/文件/Java/Java/DailyCode/08-14/src/com/dragon/java/days01.txt"); char[] buffer = new char[1024]; while (true) { int temp = fr.read(buffer, 0, buffer.length); if (temp == -1) { break; } else {
// 不能直接遍历buffer 数组,因为当该数组过长是,里面会有空字符!!
// 或者在遍历的时候去除buffer 中的空字符 --> if((int)buffer[i] == 0) --> 空字符在码表中为0.
for (int i = 0; i < temp; i++) {
if (buffer[i] == '\r' || buffer[i] == '\n'
|| buffer[i] == ' ' || buffer[i] == '\t') {
continue;
}
list.add(buffer[i]);
}
} } Collections.sort(list); char[] buffer1 = new char[list.size()]; for (int i = 0; i < list.size(); i++) { buffer1[i] = list.get(i); } fw.write(buffer1, 0, buffer1.length); } catch (IOException e) { System.out.println(e); } finally { try { fr.close(); fw.close(); } catch (IOException e) { System.out.println(e); } } } // 比较器比较字符的大小(可自主修改) public static class MyCompartor implements Comparator<Character> { @Override public int compare(Character o1, Character o2) { // if (o1 == '\n' || o2 == '\n') { // return 0; // } return o1 - o2; } } }
--> 还是没有解决多余空间的问题啊...(OK )