1

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?
4
  • Are you calling flush() or close() on the baos?
    – Michael
    Commented Dec 4, 2012 at 3:16
  • What exactly is wrong here -> "all the files following the first one written by baos are wrong (incorrect output)."? Commented Dec 4, 2012 at 3:19
  • close() would close the stream permanently, meaning I need to create a new one. Haven't thought of flush(), doesn't write() works on the same way as flush?
    – javaNoober
    Commented Dec 4, 2012 at 3:21
  • @YogendraSingh wrong as in I should be getting /9j/4AAQSkZJRgABAgEAYABgAAD/ but it says 2f/Y/+AAEEpGSUYAAQIBAGAAYAAA, totally different output
    – javaNoober
    Commented Dec 4, 2012 at 3:23

1 Answer 1

1

Perhaps the problem is that if you are assumming that encoding in base64 the concatenation of several files should give the same result as concatenating the base64 encoding of each file? That's not necessariy the case; base64 encodes groups of three consecutive input bytes to 4 ascii characters, so, unless you know that each file has a size that is a multiple of three, the base64 encoding will produce completely different outputs.

1
  • ok, took me a couple re-reads of the previous answer to get it, you are totally correct. My assumption was wrong.
    – javaNoober
    Commented Dec 4, 2012 at 4:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.