Servlet写文件最后包含二进制文件

时间:2015-08-10 14:04:01

标签: java servlets

我有一个servlet让用户从服务器下载文件。原始文件是人类可读的,但下载的文件alwyas包含文件末尾的二进制内容。

HttpSession session = request.getSession(true);
String fileName = session.getAttribute("download").toString();
System.out.println("Download file " + fileName);
File file = new File(fileName);
FileInputStream fileIn = new FileInputStream(file);

response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());

ServletOutputStream out = response.getOutputStream();
byte[] bytes = new byte[BYTES_DOWNLOAD];

while (fileIn.read(bytes, 0, BYTES_DOWNLOAD) != -1) {
    out.write(bytes, 0, BYTES_DOWNLOAD);
}

out.flush();
out.close();

提前致谢。

2 个答案:

答案 0 :(得分:2)

代码中的小错误:

byte[] bytes = new byte[BYTES_DOWNLOAD];
int count;
while ( (count = fileIn.read(bytes)) != -1) {
    out.write(bytes, 0, count);
}

答案 1 :(得分:0)

你看到了什么二进制内容?它可能是文件中的行结尾,如果有的话吗?