下载文件的推荐写法

Content-Length 能在浏览器中显示下载文件的大小
BufferedOutputStream BufferedInputStream 能优化io流
buffer 一般设置成8k 16k
在finally中close掉io


resp.setHeader("Content-Disposition", "inline; filename="
				+ URLEncoder.encode(downFilename, "UTF-8"));
		resp.setHeader("Content-Length", String.valueOf(file.length()));
		
		OutputStream out = resp.getOutputStream();
		BufferedOutputStream bout = new BufferedOutputStream(out);
		
		InputStream in = new FileInputStream(file);
		BufferedInputStream bin = new BufferedInputStream(in);
		
		byte[] buffer = new byte[16 * 1024];
		int i = -1;
		try {
			while ((i = in.read(buffer)) != -1) {
				bout.write(buffer, 0, i);
			}
		} catch (Exception e) {
			
		}finally{
			try {
				bin.close();
			} catch (Exception ignore) {
			}
			
			try {
				bout.close();
			} catch (Exception ignore) {
			}
		}

你可能感兴趣的:(下载文件)