[英]How to count characters in DOS text file including line ending?
我正在嘗試計算文本文件中的字符數。 但是,我只能計算行尾的字母和空格,而不是 \\r\\n。 我怎樣才能包括它? 下面的函數計算文件中的行數、單詞數和字符數。
public static void Count(String FILENAME, int n) throws IOException {
inFile = new BufferedReader(new FileReader(FILENAME));
String currentLine; //= inFile.readLine();
while ((currentLine=inFile.readLine()) != null) {
lines[n]++;
bytes[n]+=currentLine.length();
bytes[n]++;
String[] WORDS = currentLine.split(" "); // split the string into sub-string by whitespace
// to separate each words and store them into an array
words[n] = words[n] + WORDS.length;
if (currentLine.length()==0)
words[n]--;
}
}
一種簡單的方法是使用字符流而不是面向行的流,因為每次調用 readLine() 時,字符流都會為您提供一個字符。
public static void Count(String FILENAME, int n) throws IOException { inFile = new FileReader(FILENAME); char currentCharacter; int numCharacters = 0; String currentLine = ""; while ((currentCharacter=inFile.readLine()) != null){ if(currentCharacter == '\\n') { lines[n]++; bytes[n]+=currentLine.length(); bytes[n]++; String[] WORDS = currentLine.split(" "); words[n] = words[n] + WORDS.length; if (currentLine.length()==0) words[n]--; } currentCharacter=inFile.readLine(); currentLine += currentCharacter; numCharacters ++; }
然后總和將存儲在 numCharacters 中。 為了保留對行數和字節數等進行計數的能力,您可以在循環之前聲明一個字符串行,並將每個字符連接到循環中的末尾。 一旦你點擊了 \\n,你就知道 line 變量中有一行。 然后你可以將 line[n] 增加 1,通過 line.length() 增加 bytes[n],等等。
信息來源: https : //docs.oracle.com/javase/tutorial/essential/io/charstreams.html
計數 \\r\\n 使用 read() 方法。
readLine() 方法 讀取一行文本。 一行被視為以換行符 ('\\n')、回車符 ('\\r') 或回車符后緊跟換行符中的任何一個結束。
返回: 包含行內容的字符串,不包括任何行終止字符,如果已到達流的末尾,則返回 null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.