How to count lines in file txt android

左心房为你撑大大i 提交于 2019-12-18 07:22:33

问题


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

 void load() throws IOException        
{        
    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard,"agenda.file");
    StringBuilder text = new StringBuilder();

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;

        while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('\n');

           TextView te=(TextView)findViewById(R.id.textView1);

        }


    }
    catch (IOException e) {
        //You'll need to add proper error handling here
    }
    Button monpopb = (Button) findViewById(R.id.button13);
    monpopb.setText(text);  

} So, how to count and settext in TextView? Thank you!


回答1:


Is this what you're looking for?

void load() throws IOException        
{        
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"agenda.file");
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    TextView te=(TextView)findViewById(R.id.textView1);
    int lineCount = 0;
    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');

        lineCount++;
    }
    te.setText(String.valueOf(lineCount));

}
catch (IOException e) {
    //You'll need to add proper error handling here
}
    Button monpopb = (Button) findViewById(R.id.button13);
    monpopb.setText(text);  
}



回答2:


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("<FILE_NAME>"));
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
...


来源:https://stackoverflow.com/questions/12749655/how-to-count-lines-in-file-txt-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!