File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes BufferedWriter  to byte [] Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "BufferedWriter  to byte []" Watch "BufferedWriter  to byte []" New topic

BufferedWriter to byte []

Frank Jacobsen
Ranch Hand

Joined: May 17, 2002
Posts: 358
I want this in a byte [] is this possible, to get the file content in a byte [] after out.close();


Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
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 ]

"I'm not back." - Bill Harding, Twister
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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.
I agree. Here's the link:
subject: BufferedWriter to byte []
It's not a secret anymore!