我正在编写下载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();发布于 2011-06-23 11:14:10
bis.read返回读取的字节数。您需要在write调用中考虑到这一点。
类似于:
int rd;
while ((rd=bis.read(...)) != -1) {
bos.write(..., rd);
}发布于 2011-06-23 11:14:18
问题在于代码的以下部分:
while ((bis.read(barray, 0, BUFFER_SIZE)) != -1) {
bos.write(barray, 0, BUFFER_SIZE);
}您总是要写出BUFFER_SIZE字节的倍数,即使输入的大小不是的倍数,也是如此。这将导致在最后一个块的末尾写入垃圾。
你可以这样修正它:
int read;
while ((read = bis.read(barray, 0, BUFFER_SIZE)) != -1) {
bos.write(barray, 0, read);
}https://stackoverflow.com/questions/6453104
复制相似问题