• Post Reply Bookmark Topic Watch Topic
  • New Topic

BufferedOutputStream question

 
Frank Dijkstra
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone, I have a question regarding the BufferedOutputStream. Suppose I have the following code:


When I run this, it behaves as I would expect:



However, when I wrap the MyStream inside a BufferedOutputStream like so:


Something happens to my bytes:


Some of the bytes are suddenly below zero !?

What's going on here?
 
Richard Tookey
Bartender
Posts: 1166
17
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Keep in mind that 'byte' and 'int' values are signed. Your MyStream.write() method has an 'int' argument. You read bytes from 'is' as positive 'int' values in the range 0 to 255 and when you write them with your MyStream.write() method you write them as 'int' values so they are always positive.

When you wrap your stream with a BufferedOutputStream the bytes you write are first written to a byte array buffer inside BufferedOutputStream and then when that is filled the buffer is flushed writing the bytes to wrapped streams OutputStream.write(byte[] bytes, int offset, int len) method. The basic form of OutputStream.write(byte[] bytes, int offset, int len) just loops through the array of bytes and write the individual bytes to the OutputStream.write(int b) method but is does not first mask them using 0xff so they simply get promoted to signed 'int' which you write out as signed 'int' !

If this is a problem to you then just use

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!