InputStream is = new FileInputStream(filePath);
byte[] b = new byte[8 * 1024];
int length = -1;
OutputStream out = response.getOutputStream();
while ((length = is.read(b)) != -1) {
out.write(b, 0, length);
}
out.close();
is.close();
1:里面为什么length=-1 等于其他不行么?
2:可以这样写吗:
int length=is.read(b);
while(length!=-1){
..............................
}
1:里面为什么length=-1 等于其他不行么?
可以写成其他值,因为 while ((length = is.read(b)) != -1) 会对length先赋值,再比较。所以什么值都会被覆盖掉。
同样的例子还有
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("filepath")));
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = reader.readLine()) != null) {
buffer.append(str);
}
2:可以这样写吗:
int length=is.read(b);
while(length!=-1){
..............................
}
这个不可以这么写,因为这样写的话,文件有内容的话,就死循环了,空文件不执行。达不到读取的效果,正确的实例是每次读取8 * 1024个字节,,读到文件结尾。
有时间也可以研究一下源码:
额,这里这么写是因为每次is.read(b)是读入一行。然后计算其长度,长度=-1说明读到最后读完了,如果写在外面,那么length永远不变。会死循环的
1:里面为什么length=-1 等于其他不行么?
is.read(b),length=-1 表示 文件内容已经全部读完
2:要改写的话只能
do {
if(length !=-1) out.write(b, 0, length);
length = is.read(b);
} while (length!=-1);
原理是 要先读即(is.read(b))即在有内容的情况下write,读取完毕退出循环
而
int length=is.read(b);
while(length!=-1){
..............................
}
length仅仅读取了文件一次,然后进行(length !=-1)循环,因为length的值不发生变化(length !=-1)永远为true,即进入死循环