<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
org.apache.commons.io.IOUtils;
案例
@WebServlet("/servletA")
public class ServletA extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
FileInputStream fis = new FileInputStream("D://a.jpg");
ServletOutputStream os = resp.getOutputStream();
/*byte[] buff = new byte[1024];
int len = 0;
while ((len = fis.read(buff))!=-1){
os.write(buff,0,len);
}*/
/* 上面代码替换为IOUtils.copy(fis,os);
需添加依赖,使用import org.apache.commons.io.IOUtils;中的IOUtils.copy();
* <dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
*/
IOUtils.copy(fis,os);
fis.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}