How to count lines in file txt android

前端 未结 2 829
囚心锁ツ
囚心锁ツ 2020-12-18 16:45

Can\'t understand how to count lines. Here is my code.

 void load() throws IOException        
{        
    File sdcard = Environment.getExternalStorageDire         


        
2条回答
  •  时光说笑
    2020-12-18 17:06

    For already existing text files its possible to use LineNumberReader class and LineNumberReader.skip() and LineNumberReader.getLineNumber() methods to get total lines count in file. Something like that:

    ...
    InputStream inputStream = new FileInputStream(new File(""));
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    LineNumberReader lineNumberReader = new LineNumberReader(bufferedReader);
    try {
        lineNumberReader.skip(Long.MAX_VALUE);
    } catch (IOException e) {
        e.printStackTrace();
    }
    linesInFile = lineNumberReader.getLineNumber() + 1;  // because line numbers starts from 0
    ...
    

提交回复
热议问题