1

I am using BufferedReader to get a String from a .txt File

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

    }

Than I display that String in a TextView But it displays null and than my String

nullThis is file 1 rather than This is file 1

How can I fix this??

Cœur
  • 37,241
  • 25
  • 195
  • 267
Eddie
  • 31
  • 8

4 Answers4

4

You are using:

String str = null;

And then

str += read.readLine() + "\n";

Which is

str = str + read.readLine() + "\n";

So, after variable substitution, we get:

str = null + read.readLine() + "\n";

And this means we join it with null, which produces "null" intentionally.

Try one of these lines (only one):

String str = "";
String str = new String ();
Top Sekret
  • 748
  • 5
  • 21
3

Try this out!

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

}
android_griezmann
  • 3,757
  • 4
  • 16
  • 43
  • Ohh... I thought `String = null` sets the `String` to equal nothing. – Eddie Jan 03 '17 at 06:05
  • @Eddie just follow [this link](http://stackoverflow.com/questions/4802015/difference-between-null-and-empty-java-string) and you will get a very clear idea. – android_griezmann Jan 03 '17 at 06:07
2

You can use StringBuilder instead of String. It has better performance since String is immutable.

[use StringBuffer if you want it to be thread safe].

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");
    }
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
2

Initialize it like

String str = "";
Waqas Ahmed
  • 153
  • 11