Kotlin - 实现流写入到File

转自: Kotlin 中实现流的读取的方法
https://www.jianshu.com/p/31ce8caefa25


我们知道java中IO操作是一份很重要的知识点,运用IO知识可以完成许多使用的操作,在Java中,提供了许多方法来进行流的读写操作,但是Kotlin 中呢?要怎么写呢?恰巧今天写Kotlin页面的时候遇到了,在Java 中很普通甚至普遍的写法,在Kotlin 中居然一直是报错的状态:

FileOutputStream fos = new FileOutputStream(file);
           BufferedInputStream bis = new BufferedInputStream(is);
           byte[] buffer = new byte[1024];
           int len;
           int total = 0;
           while ((len = bis.read(buffer)) != -1) {
               fos.write(buffer, 0, len);
               total = total + len;
               //获取当前下载量
               pd.setProgress((total / 1024));
           }
           fos.close();
           bis.close();
           is.close();
           return file;

其中 while ((len = bis.read(buffer)) != -1) {}在java 中的写法是非常普遍的,但是到了Kotlin 中呢?
就是这个样子:

 val fos = FileOutputStream(file)
        val bis = BufferedInputStream(`is`)
        val buffer = ByteArray(1024)
        val len: Int
        var total = 0
        while ((len = bis.read(buffer)) != -1) {
            fos.write(buffer, 0, len)
            total = total + len
            //获取当前下载量
            pd.progress = total / 1024
        }
        fos.close()
        bis.close()
        `is`.close()
        return file

其中while ((len = bis.read(buffer)) != -1)会疯狂提示错误! 意思是说参数是不被允许的,what?怎么会这样呢,百度了一下,原来Kotlin 中等式不是一个表达式,这种写法是不被允许的,所有只有选择其他方法了,后来发现了Kotlin中的also扩展函数对,就是这货,用这货写就可以了:

            while (((bis.read(buffer)).also { len = it }) != -1) {
                fos.write(buffer, 0, len)
                total += len
                //获取当前下载量
                pd.progress = total / 1024
            }
            fos.close()

所以现在这种就是很好的写法了,运行起来跟java中的效果是一样的。
最后,没事多学习,有空多挣钱,新的一年,大家继续努力

你可能感兴趣的:(Kotlin - 实现流写入到File)