[英]BufferedOutputStream writing garbage data
我正在编写读取html文件并将其写入servletOutputStream
下载servlet,就在传输文件的问题上,它正在添加一些垃圾数据,对此有任何建议,
下面是我为此使用的代码
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
返回读取的字节数。 您需要在write
调用中考虑到这一点。
就像是:
int rd;
while ((rd=bis.read(...)) != -1) {
bos.write(..., rd);
}
问题出在代码的以下部分:
while ((bis.read(barray, 0, BUFFER_SIZE)) != -1) {
bos.write(barray, 0, BUFFER_SIZE);
}
你总是写出的倍数BUFFER_SIZE
字节, 即使你输入的大小不是一个多BUFFER_SIZE
。 这导致在最后一块的末尾写入垃圾。
您可以这样修复它:
int read;
while ((read = bis.read(barray, 0, BUFFER_SIZE)) != -1) {
bos.write(barray, 0, read);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.