0

我遍历 SDCard 目录,读取每个文件中的文本,并将文本写入动态添加的 textViews。每个文件都包含换行符,我认为问题出在哪里。我搜索了 SO 和 Google,尝试了一些建议,现在我的代码返回并打印每个文本文件两次。第一个只包含文本,直到第一个换行符,第二个完全按照我的需要打印文本。示例文本文件 test.txt

    This is a test.
    And I cannot make it work

所需的输出是

    test.txt
    This is a test.
    And I cannot make it work

第一次添加视图时,我得到

    test.txt
    This is a test.

第二次,我得到了想要的输出。它对所有 txt 文件执行此操作

这是我的代码

    String sdcard = Environment.getExternalStorageDirectory() + "/.BELIEVE/PushMessages/";

    // go to your directory
    File fileList = new File( sdcard );

    //check if dir is not null
    if (fileList != null){

        // so we can list all files
        File[] filenames = fileList.listFiles();

        // loop through each file
        for (File tmpf : filenames){

        StringBuilder text = new StringBuilder();

            try {
            BufferedReader br = new BufferedReader(new FileReader(tmpf));
            String name = tmpf.getName();
            String line;

            while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('\n');
            TextView title = new TextView(PushMessagesPage.this);
            TextView message = new TextView(PushMessagesPage.this);
            ll.addView(title);
                title.setLayoutParams(textViewParams);
            title.setTextAppearance(this, android.R.attr.textAppearanceLarge);
            title.setTextColor(0xff33b5e5);
            title.setText(name);
            ll.addView(message);    
                            message.setLayoutParams(textViewParams);
            message.setTextColor(0xffffffff);
            message.setText(text);

这段代码有什么问题?

4

1 回答 1

1

你的代码应该是这样的。

for (File tmpf : filenames) {
    StringBuilder text = new StringBuilder();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(tmpf));
        String name = tmpf.getName();
        String line;

        TextView title = new TextView(StackDemosActivity.this);
        ll.addView(title);
        title.setLayoutParams(textViewParams);
        title.setTextAppearance(this,
                android.R.attr.textAppearanceLarge);
        title.setTextColor(0xff33b5e5);
        title.setText(name);

        TextView message = new TextView(StackDemosActivity.this);
        ll.addView(message);
        message.setLayoutParams(textViewParams);
        message.setTextColor(0xffffffff);

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

    } catch (Exception e) {
        e.printStackTrace();
    }
}
于 2013-08-27T06:18:33.650 回答