I\'m writing a simple program in Java and it requires reading data from a text file. However, I\'m having trouble counting lines. The issue seems generic enough for a simple
You can not use the scanner to count the no of line in file because as default scanner uses white space to separate tokens. I would suggest to use BufferReader and readline method.
http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html
private Integer getNoOfLines( String fileName) throws FileNotFoundException,
IOException {
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
List lineList = new ArrayList();
while ((strLine = br.readLine()) != null) {
lineList.add(strLine);
}
in.close();
return lineList.size();
}