1

无法理解如何计算行数。这是我的代码。

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

那么,如何在 TextView 中对文本进行计数和设置呢?谢谢!

4

2 回答 2

3

这是你要找的吗?

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);  
}
于 2012-10-05T15:54:11.380 回答
3

对于已经存在的文本文件,可以使用LineNumberReaderLineNumberReader.skip()LineNumberReader.getLineNumber()方法来获取文件中的总行数。像这样的东西:

...
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
...
于 2018-12-05T19:42:18.323 回答