I need to read multiple small files and append them into a bigger single file.
Base64OutputStream baos = new Base64OutputStream(new FileOutputStream(outputFile, true));
for (String fileLocation : fileLocations) {
InputStream fis = null;
try
{
fis = new FileInputStream(new File(fileLocation));
int bytesRead = 0;
byte[] buf = new byte[65536];
while ((bytesRead=fis.read(buf)) != -1) {
if (bytesRead > 0) baos.write(buf, 0, bytesRead);
}
}
catch (Exception e) {
logger.error(e.getMessage());
}
finally{
try{
if(fis != null)
fis.close();
}
catch(Exception e){
logger.error(e.getMessage());
}
}
}
All pretty standard, but I'm finding that, unless I open a new baos per input file (include it inside the loop), all the files following the first one written by baos are wrong (incorrect output).
The questions:
- I've been told that opening/closing an outputstream back and forth for the same resource is not a good practice, why?
- Why using a single output stream is not delivering the same result as multiple separate ones?