我必須編寫讀取文本文件的代碼,並告訴我文件中有多少行和字符。我有它的工作,但後來我意識到我不得不忽略空白的差距,所以我寫了一個方法來做到這一點。它適用於一行,但如果我有多行,它似乎計算任何空格。任何幫助,將不勝感激需要統計文本文件中的字符
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Inputfile {
public static void main(String[] args) {
System.out.println("file name:");
Scanner sc = new Scanner(System.in);
String fn = sc.next();
int nrl = 0, nChar = 0;// nrl for number of lines
String line;// get line content variable
try {
File fs = new File("C:/" + fn);
nChar = length_ws(fs);
FileReader fr;// for reading file
fr = new FileReader(fs);
LineNumberReader lnr = new LineNumberReader(fr);
while (lnr.readLine() != null) {
nrl++;// count number of lines
}
JOptionPane.showMessageDialog(null, "number of lines:" + nrl + "\ntotal number of chars:" + nChar);
lnr.close();
fr.close();// close file
} catch (FileNotFoundException ex) {
System.err.println("File not found");
System.exit(0);
} catch (IOException ex) {
}
}
public static int length_ws(File f) throws IOException {
FileReader fr = null;
fr = new FileReader(f);
int i;
i = 0;
int c = 0;
do {
c = fr.read();// read character
if (c!= ' ') // count character except white space
i++;
} while (c != -1);
return i - 1;// because the is counted even the end of file
}
}
有你的代碼中的許多可能出現的問題。您正在使用'read()'方法來讀取字節,而不是字符,因此您正在假設在一個字節上寫入字符的文件的編碼。它可能與ASCII工作,但如果你將使用像UTF16編碼,你會得到一些問題。同樣'if(c!='')'只忽略空格,但會包含所有其他字符,如製表符'\ t',行分隔符'\ n'' \ r'或標點符號。在讀取行時,您應該簡單地處理字符的計算(使用String和Character類中的方法從行中獲取和測試這些字符)。 – Pshemo
這聽起來像你可能需要學習如何使用調試器來逐步執行代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:** [如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver