--> 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 )