I'm trying count the number of characters in a text file. However, I can only count the letters and whitespace, not \\r\\n at the end of the line. How can I include it? The function below counts the number of lines, words, and characters in a file.
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]--;
}
}
One simple way would be to utilize Character Streams instead of Line-oriented Streams since character streams give you one character each time you call 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 ++; }
And then the sum would be stored in numCharacters. To retain the ability to count lines and bytes and such, you could have a String line declared before the loop and concatenate each character to the end of it in the loop. Once you hit a \\n, you know that you have one line in the line variable. Then u could increment line[n] by one, increase bytes[n] by line.length(), etc.
source of info: https://docs.oracle.com/javase/tutorial/essential/io/charstreams.html
for counting \\r\\n use read() method.
readLine() method Reads a line of text. A line is considered to be terminated by any one of a line feed ('\\n'), a carriage return ('\\r'), or a carriage return followed immediately by a linefeed.
Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.