• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

BufferedWriter to byte []

 
Frank Jacobsen
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want this in a byte [] is this possible, to get the file content in a byte [] after out.close();




Frank

 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your choices are...

(1) After finishing writing the file, read it back into a byte array. Easy, but maybe a bit inefficient.

(2) Use a "tee stream" to send the data to a ByteArrayOutputStream as well as to a FileOutputStream. You'd need an OutputStreamWriter in the chain somewhere. There's no such thing as a "tee stream" in Java 1.4, which I currently use, so I have my own. Maybe later Java, or third-party free library, has one.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Considering the file is referred to as "temp", I'm not sure it's even needed. Peter's solutions assume you want to write a file and get a byte[] array. If you don't need a file, and just want the byte[], then you can write it directly:

Note the OutputStreamWriter to convert between a Writer and an OutputStream. The one shown uses your platform default character encoding, but you can use a different constructor to specify a different particular encoding if you like.

Incidentally, in this example the BufferedWriter doesn't really do anything useful; you might as well omit it and write with the OutputStream.
[ April 10, 2007: Message edited by: Jim Yingst ]
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed. If you were only creating the file as part of your attempt to get the byte array, then Jim's solution is much better. On the other hand, if you really did need a file containing the bytes as well, then either of my suggestions is still valid.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic