weixin_43490664 2019-03-15 12:47 采纳率: 100%
浏览 360
已采纳

关于io流的简单问题!请指教!!!!!!!!!

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){
..............................
}
  • 写回答

3条回答 默认 最新

  • TinerSky 2019-03-15 13:56
    关注

    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个字节,,读到文件结尾。

    有时间也可以研究一下源码:
    图片说明

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备