我正在使用BufferedReader
从String
文件中获取.txt
BufferedReader read = new BufferedReader(
new InputStreamReader(getAssets().open(name)));
BufferedReader count = new BufferedReader(
new InputStreamReader(getAssets().open(name)));
String line;
String str = null;
while((line = count.readLine()) != null)
{
str += read.readLine() + "\n";
}
我在String
中显示TextView
但它显示的是null,而不是我的String
nullThis is file 1
而不是
This is file 1
我该如何解决这个问题?
答案 0 :(得分:3)
试试这个!
BufferedReader read = new BufferedReader(
new InputStreamReader(getAssets().open(name)));
BufferedReader count = new BufferedReader(
new InputStreamReader(getAssets().open(name)));
String line;
String str = "";
while((line=count.readLine())!=null)
{
str += read.readLine() + "\n";
}
答案 1 :(得分:3)
您正在使用:
String str = null;
然后
str += read.readLine() + "\n";
哪个是
str = str + read.readLine() + "\n";
因此,在变量替换后,我们得到:
str = null + read.readLine() + "\n";
这意味着我们将其与null结合,有意产生"null"
。
尝试其中一行(仅一个):
String str = "";
String str = new String ();
答案 2 :(得分:2)
您可以使用StringBuilder
代替String
。它具有更好的性能,因为String
是不可变的。
[如果您希望它是线程安全的话,请使用StringBuffer
。
BufferedReader read = new BufferedReader(
new InputStreamReader(getAssets().open(name)));
BufferedReader count = new BufferedReader(
new InputStreamReader(getAssets().open(name)));
String line;
StringBuilder str = new StringBuilder();
while((line = count.readLine()) != null)
{
str.append(read.readLine()).append("\n");
}
答案 3 :(得分:2)
将其初始化为
String str = "";