• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Efficient I/O in Servlets

 
tom walters
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is an efficient way to read from an input stream and write to an outputstream when you do not know the number of bytes in the inputstream?
I am currently doing the following:
InputStream is = getInputStream();//helper method
ServletOutputStream sos = response.getOutputStream();
byte b;
while((b = (byte)is.read()) != -1)
sos.write(b);
is.close();
sos.flush();
sos.close();
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13073
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although the method you are using is safe and simple, the prefered method is to use a BufferedInputStream / BufferedOutputStream or one of the related classes for reader and writer.
You can use the available() method of BufferedInputStream to see how many bytes you can safely read into a byte[]
Whether it is worth the trouble to use a different method would depend on how often you have to do this and how much data is transferred.
Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic