BufferedOutputStream 写入垃圾数据
我正在编写下载 servlet,它读取 html 文件并写入 servletOutputStream
,传输的文件末尾的问题是添加一些垃圾数据,对此有任何建议,
下面是我为此使用的代码
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();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
bis.read
返回读取的字节数。您需要在write
调用中考虑到这一点。像这样的东西:
bis.read
returns the number of bytes read. You need to take that into account in yourwrite
call.Something like:
问题出在代码的以下部分:
您总是写出
BUFFER_SIZE
字节的倍数,即使您的输入大小不是BUFFER_SIZE< 的倍数/代码>
。这会导致在最后一个块的末尾写入垃圾。
你可以像这样修复它:
The problem is with the following part of your code:
You are always writing out a multiple of
BUFFER_SIZE
bytes, even if the size of your input isn't a multiple ofBUFFER_SIZE
. This results in garbage being written at the end of the last block.You can fix it like so: