Kuang Lin Kuang Lin - 1 month ago 8
Java Question

repeated lines when I use char[] in while loop for reading text file in Android

I use char[] as a buffer to restore the text BufferedReader reads.
and with while loop I read all the text file 200 chars per loop until it hits -1.
This is my code.

textView=(TextView) findViewById(R.id.textview);
textView.setMovementMethod(new ScrollingMovementMethod());
String line;
char[] buffer=new char[200];
InputStream is = this.getResources().openRawResource(R.raw.test);
InputStreamReader isr= new InputStreamReader(is);
BufferedReader bfr= new BufferedReader(isr);
try {
String s="";
while(true)
{ int temp= bfr.read(buffer,0,buffer.length);
if(temp<0)
break;
else s=s+new String(buffer);
}
textView.setText(s);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}


But my result came out wring.
It repeat the last 100 chars two times.
I can't understand why.

EJP EJP
Answer
s=s+new String(buffer);

That should be

s=s+new String(buffer, 0, temp);

You're ignoring the count returned by read(). You should probably also add a charset parameter.

But you shouldn't read entire files into memory. Process it a piece at a time.