java io 文件下载

/**
	 *  文件下载
	 * @param response
	 * @param downloadPath
	 * @param docName
	 */
	public void downLoadFile(
			HttpServletResponse response,String downloadPath, String docName) {
		response.setContentType("text/html;charset=utf-8");
	
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		
		File file = new File(downloadPath);

		try {
			response.addHeader("Content-Length", String.valueOf(file.length()));
			byte[] buff = new byte[2048];
			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(response.getOutputStream());
			int bytesRead;
			while ((bytesRead = bis.read(buff, 0, buff.length)) != -1) {
				bos.write(buff, 0, buff.length);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(bis !=null){
					bis.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(bos !=null){
					bos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}
}

  

原文地址:https://www.cnblogs.com/newlangwen/p/7440888.html