RT,一直有个疑问,len = is.read(flush)要放在while中进行判断是否已经读到文件没有数据。
放在while循环体中不行吗?
我自己试了一下,一直无法跳出,有点奇怪。
代码如下:
InputStream is = item.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
byte flush[] = new byte[10];
int length = 0 ;
while(-1 != length) {
length = is.read(flush);
fos.write(flush,0,length);
}
fos.close();
查过源码,按我的理解:
如果文件是12个字节
第一次运行,true(-1 != 0)flush.len=10, length=10;
第二次运行,true(-1 != 10) flush.len = 2, length= 2
第三次运行,true(-1 != 2) flush.len = -1 ,length = -1;
第四次运行,false(-1 != -1)这时候该循环就跳出了吧。
InputStream is = item.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
byte flush[] = new byte[10];
int length = 0 ;
while(-1 != (length= is.read(flush))) {
fos.write(flush,0,length);
}
fos.close();
如果文件是12个字节
第一次运行,true(-1 != 10)flush.len=10, length=10;
第二次运行,true(-1 != 2) flush.len = 2, length= 2
第三次运行,false(-1 != -1),跳出循环。
按理来说,不论哪种情况总归是会跳出循环的,至多前面一种写法,效率低一些,但不知道为什么第一种情况跳不出来。