关于InputStream.read()方法,我今天发现了这样一段代码。
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletInputStream in=req.getInputStream();
String filePath=getServletContext().getRealPath("/body.out");
FileOutputStream out=new FileOutputStream(filePath);
int total_len=req.getContentLength();
byte[] buf=new byte[total_len];
for(int read_len=0,reading_len=0;read_len<total_len;read_len+=reading_len)
{
reading_len=in.read(buf,read_len,total_len-read_len);
}
out.write(buf,0,total_len);
in.close();
out.close();
}
也许会有疑惑,这个循环是拿来做什么的,据我所了解的几种read返回的情况如下
- 当读到EOF时,返回-1;
- 当读取到指定字节的长度时,返回指定字节的长度
- 当未读取到指定字节长度,但已经读取完缓冲区,返回读取到的长度
在这个代码片段中,如果按照正常想法而言,读取一次刚好能把数据读完,那么这个循环的作用在什么地方?书上讲了这样一个数据的读取模型,如下: