public class HelloServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置浏览器响应的mime类型 response.setContentType("application/msword"); //从服务器中获取要下载的文件的路径 String realPath = getServletContext().getRealPath("/error/myword.docx"); File file = new File(realPath); try { //获取该文件的输入流 FileInputStream inputStream = new FileInputStream(file); //通过response获取ServletOutputStream对象(out) ServletOutputStream outputStream = response.getOutputStream(); //通过字节流的方式将文件写会浏览器 int b = 0; byte[] buffer = new byte[1024]; while (b != -1){ b = inputStream.read(buffer); //写到输出流(out)中 outputStream.write(buffer,0,b); } inputStream.close(); outputStream.close(); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } }