java servlet通过url下载文件

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		response.setContentType("text/plain");
		response.setHeader("Content-disposition", "attachment; filename=1.txt");//filename是下载下来的文件名,可以跟原文件名不一样
		System.out.println("--1---");
//		这里的路径是编译后的路径
		InputStream in =this.getServletContext().getResourceAsStream("/WEB-INF/classes/resources/config/conf.properties");
		OutputStream out = response.getOutputStream();
		System.out.println("---2--");
		byte[] buffer = new byte[1048];
		int len = -1;
		if(in==null) {
			System.out.println("not exist");
		}
		while ((len = in.read(buffer)) > 0) {
			out.write(buffer, 0, len);
		}
		out.flush();
		if (in != null) {
			in.close();
			System.out.println("in.close");
		}
		out.close();
	}

 

你可能感兴趣的:(java,java)