Monday, August 25, 2014

Creating a file from ByteArrayOutputStream in Java.

When we are dealing with data over the line, our option is bytes and one of the handy Class in Java to deal with bytes and streams together is ByteArrayOutputStream. When ever you want to write some bytes to specific file while receiving the data you just need to use the method writeTo().  

Code to Create a file from ByteArrayOutputStream in Java:

 OutputStream outStream = null;  
 ByteArrayOutputStream byteOutStream = null;  
 try {  
   outStream = new FileOutputStream("fileNameToSave");  
   byteOutStream = new ByteArrayOutputStream();  
   // writing bytes in to byte output stream  
   byteOutStream.write(bytes); //data  
 } catch (IOException e) {  
 } finally {  

The code it self pretty straight forward. We are just creating a new file with specified name and keeping aside. In very next line creating a stream to capture the bytes. Once the stream captured the bytes we are telling the stream that, sit your self in the file.

And as a side note, do not forget to close all the streams/resources you used earlier. Leaving streams open costs more in terms of memory as-well as performance. In above code, I closed one stream an example. Please identify remaining and close each and every stream.

That is all to create a file with specified name with incoming byte array stream.

No comments:

Post a Comment