Code refactoring: I would recommend you not write to ByteArrayOutputStream, then convert to a byte[], then write the byte[] to a FileOutputStream.