Android 为什么同一个字符串有多个结果,为什么它们不同
我在SD卡目录中循环,读取每个文件中的文本,并将文本写入动态添加的TextView。 每个文件都包含换行符,我认为这是问题所在。 我已经搜索了SO,Google尝试了一些建议,现在我的代码返回并打印每个文本文件两次。第一个只包含文本,直到第一个换行符,第二个按我需要的方式打印文本。 示例文本文件test.txtAndroid 为什么同一个字符串有多个结果,为什么它们不同,android,stringbuilder,Android,Stringbuilder,我在SD卡目录中循环,读取每个文件中的文本,并将文本写入动态添加的TextView。 每个文件都包含换行符,我认为这是问题所在。 我已经搜索了SO,Google尝试了一些建议,现在我的代码返回并打印每个文本文件两次。第一个只包含文本,直到第一个换行符,第二个按我需要的方式打印文本。 示例文本文件test.txt This is a test. And I cannot make it work 所需输出为 test.txt This is a test.
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);
此代码有什么问题?您的代码应该是这样的
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();
}
}
message.setText(文本)你们的问题解决了吗?Sunil,昨晚我读了你们的评论后,检查了我上面的代码,很明显你们是绝对正确的。谢谢你的建议,我对你的评论投了赞成票!!是的,先生,这个答案100%有效。当我陷入困境时,我尝试了太多不同的东西,以至于我的代码变得混乱不堪。这是一个很好很干净的回答!还应该注意的是,setTextAppearence(这个,android.R.attr.textAppearenceLarge)只适用于API13及以下版本。如果您使用的是14或更高版本,那么它应该是setTextAppearence(这是android.R.style.TextAppearence\u Large)