简体   繁体   中英

BufferedOutputStream writing garbage data

I am writing download servlet that reads a html file and writes to servletOutputStream , the problem right at the of the file transferred it is adding some garbage data any suggestions about this,

below is code I am using for this


        int BUFFER_SIZE = 1024 * 8;
        servOut   = response.getOutputStream();
        bos       = new BufferedOutputStream(servOut);
        fileObj = new File(file);
        fileToDownload = new FileInputStream(fileObj);
        bis = new BufferedInputStream(fileToDownload);
        response.setContentType("application/text/html");
          response.setHeader("ContentDisposition","attachment;filename="+dump+".html");
        byte[] barray = new byte[BUFFER_SIZE];
        while ((bis.read(barray, 0, BUFFER_SIZE)) != -1) {
            bos.write(barray, 0, BUFFER_SIZE);
        }
        bos.flush();

bis.read returns the number of bytes read. You need to take that into account in your write call.

Something like:

int rd;
while ((rd=bis.read(...)) != -1) {
     bos.write(..., rd);
}

The problem is with the following part of your code:

        while ((bis.read(barray, 0, BUFFER_SIZE)) != -1) {
            bos.write(barray, 0, BUFFER_SIZE);
        }

You are always writing out a multiple of BUFFER_SIZE bytes, even if the size of your input isn't a multiple of BUFFER_SIZE . This results in garbage being written at the end of the last block.

You can fix it like so:

        int read;
        while ((read = bis.read(barray, 0, BUFFER_SIZE)) != -1) {
            bos.write(barray, 0, read);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM