my dog learned polymorphism*
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 OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "BufferedWriter  to byte []" Watch "BufferedWriter  to byte []" New topic
Author

BufferedWriter to byte []

Frank Jacobsen
Ranch Hand

Joined: May 17, 2002
Posts: 353
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

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
Wanderer
Sheriff

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: http://aspose.com/file-tools
 
subject: BufferedWriter to byte []