[英]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, 我正在编写读取html文件并将其写入
servletOutputStream
下载servlet,就在传输文件的问题上,它正在添加一些垃圾数据,对此有任何建议,
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. bis.read
返回读取的字节数。 You need to take that into account in your write
call. 您需要在
write
调用中考虑到这一点。
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
. 你总是写出的倍数
BUFFER_SIZE
字节, 即使你输入的大小不是一个多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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.