文件下载IO流代码参考

private void sendFile(HttpServletRequest request,
HttpServletResponse response, File file, String fileName)
throws FileNotFoundException, IOException {
FileInputStream fileInput = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fileInput);

ByteArrayOutputStream bArray = new ByteArrayOutputStream();

byte[] tempByte = new byte[1024];
while (true) {
int tempBL = in.read(tempByte);
if (tempBL == -1) {
break;
}
bArray.write(tempByte, 0, tempBL);
}
response.setContentType("application/octet-stream; charset="
+ Live800Define.CHATSET);

response.setHeader("Content-disposition", "attachment; filename="
+ URLEncoder.encode(fileName, Live800Define.CHATSET).replace(
"+".charAt(0), " ".charAt(0)));

// new String(fileName.getBytes(Live800Define.CHATSET), "ISO8859_1"));

javax.servlet.ServletOutputStream out = response.getOutputStream();
tempByte = bArray.toByteArray();
response.setContentLength(tempByte.length);
out.write(tempByte, 0, tempByte.length);
out.flush();
out.close();
fileInput.close();
in.close();

}

你可能感兴趣的:(servlet)