Only 49 hours left in the trailboss' kickstarter!

New rewards and stretch goals. CLICK HERE!



  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how to determine the buffer size  RSS feed

 
zb cong
Ranch Hand
Posts: 416
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello
one the difference between old io and new io is that the old io read data BYTE-BY-BYTE,but the new io read data IN CHUNKS.
sample code snippet about the nio socket reading as following:

ByteBuffer buffer=ByteBuffer.allocate(1024);
.......
.......
socketChannel.read(buffer);.


the socket read the data in chunk to the buffer,not like the old io that read data by byte-by-byte loop.this machanism can be efficent.but also introduce a new problem,that is:how can i determine the buffer size in the developing time,because i don't know the message length that come from the socket,it is RANDOM,as you can see.i assign a 1024-byte buffer in the code snippet,but if the message length is 2048 in the run time,my application will throw the overflow exception,who have a good idea to deal with such problem?

thank you
 
Joe Ess
Bartender
Posts: 9406
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java.io.InputStream has always had a method with the signature

IO would have been ridiculously inefficient without such a method. To read an input which is larger than the buffer b, we do multiple reads and accumulate the input in another structure, say a ByteArrayInputStream until the above method returns -1 indicating End Of File.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!