Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

InputStreamReader fails when buffer size is large  RSS feed

 
Dilshan Edirisuriya
Ranch Hand
Posts: 299
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following coding,

//get the socket connection here
InputStream streamFromSocket = socket.getInputStream();
InputStreamReader streamReader = new InputStreamReader(streamFromSocket, "UTF-8");

while(mycondition) {

streamReader.read(charBuffer, 0, CHAR_BUFFER_SIZE);

//rest of the logic

}

The "socket" reference holds a reference to a active socket. From InputStreamReader it receive xml data chunks. The question is with the "streamReader.read(charBuffer, 0, CHAR_BUFFER_SIZE)" method.
When I define the charBuffer size as 100 and more the received xml data chunks get corrupted (sometimes very large xml data chunks). But when I define it a less value like 10 it works fine. I applied efficient practices like Buffering the input stream but still It did not solve. So what is the possible reason for such a corruption in input stream and what is the relationship of this with the buffer size.

Thank you.
 
Rob Spoor
Sheriff
Posts: 20895
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My initial guess: the buffer can't be completely filled but you still use all of its contents. There is a reason this method returns an int though.

So retrieve the number of characters read, and use it:

Of course I haven't put the test against -1 (end of stream) in there, but this is the basic idea.
 
Dilshan Edirisuriya
Ranch Hand
Posts: 299
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob.

It solved the problem.

int len = streamReader.read(charBuffer, 0, CHAR_BUFFER_SIZE);

According to the coding I observed that the "len" size tends to differ when we are passing large data set through the stream. So based on that, I read the stream.

Thank you
[ October 09, 2008: Message edited by: Dilshan Edirisuriya ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!