读取pdf
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/pdf"); InputStream in = getServletContext().getResourceAsStream("/WEB-INF/java.pdf"); OutputStream out = response.getOutputStream(); writeBytes(in,out); } private void writeBytes(InputStream in, OutputStream out) throws IOException { byte[] buffer =new byte[1024]; int length = -1; while ((length=in.read(buffer))!=-1) { out.write(buffer,0,length); } in.close(); out.close(); }
读取PNG
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/png"); File file = new File("F:\OneDrive\身份证\888.jpg");//获取文件流 System.out.println(file.getName()); InputStream in = new FileInputStream(file);//文件流转输入流 OutputStream out = response.getOutputStream();/获取输出流 writeBytes(in,out);//输出文件 } private void writeBytes(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int length=-1; while((length=in.read(buffer))!=-1) { out.write(buffer, 0, length); } in.close(); out.close(); }