Scanner on text file hasNext() is infinite

后端 未结 4 1570
别跟我提以往
别跟我提以往 2020-12-03 16:17

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

4条回答
  •  没有蜡笔的小新
    2020-12-03 16:38

    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();
    }
    

提交回复
热议问题