我正在嘗試查找給定文本文件中的字符數。衝突的字符數
我試過使用掃描儀和BufferedReader,但我得到了衝突的結果。在我添加一個新的行字符後,使用掃描器連接每一行。例如。像這樣:
FileReader reader = new FileReader("sampleFile.txt");
Scanner lineScanner = new Scanner(reader);
String totalLines = "";
while (lineScanner.hasNextLine()){
String line = lineScanner.nextLine()+'\n';
totalLines += line;
}
System.out.println("Count "+totalLines.length());
這將返回真正的字符數我的文件,該文件是5799
而當我使用:
BufferedReader reader = new BufferedReader(new FileReader("sample.txt"));
int i;
int count = 0;
while ((i = in.read()) != -1) {
count++;
}
System.out.println("Count "+count);
我得到5892.
我知道使用如果只有一行,lineScanner會關閉,但對於我的文本文件,我會得到正確的輸出。
此外,在記事本++以字節爲單位的文件長度是5892,但沒有空格字符計數是5706
所以你的問題到底是什麼? – PTBG
@PTBG我的問題是爲什麼使用掃描儀或緩衝讀取器得到不同的答案? – user557240
好吧,我剛剛檢查過,區別在於掃描器不包括'\ r'。如果我在linux上運行這個代碼,我會得到不同的輸出嗎? – user557240