I have the following function , which counts the lines in a simple file. This file is consisting of integers separated by newlines , but the problem is that it's going one character at a time. And so if the last line has 2 digits, it will only return the 2nd digit as the final output:
Here is my code :
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
int lastline = 0;
boolean empty = true;
while ( (readChars = is.read(c)) != -1) {
//System.out.println (" The array is + readChars " + readChars + " !!!" );
for (int i = 0; i < readChars; ++i){
Byte b = c[i];
int xx = b.intValue();
lastLine = xx;
if (c[i] == '\n'){
++count;
empty = true;
} else {
empty = false;
}
} // END inner- FOR-LOOP
}// END WHILE-LOOP
if (!empty) {
count++;
}
int asciiVal = lastLine;
int lastLine2 = Character.getNumericValue(asciiVal);
System.out.println("the last line was " + lastLine2);
return count;
} finally {
is.close();
}
}//END method countLines
Here's a sample text file of the input it's reading :
1
2
3
4
5
6
7
8
9
17
any tips appreciated. I want to learn better Java encoding, IO, etc topics related to this also. thank