循环浏览SDCard目录,读取每个文件中的文本,并将文本写入动态添加的textViews。 每个文件都包含换行符,我认为问题出在哪里。 我已经搜索过了,谷歌尝试了一些建议,现在我的代码返回并打印每个文本文件两次。第一个只包含文本,直到第一个换行符,ssecond确切地打印文本我需要的方式。 示例文本文件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);
此代码有什么问题?
答案 0 :(得分: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();
}
}