Kotlin - 實現(xiàn)流寫入到File

轉(zhuǎn)自: Kotlin 中實現(xiàn)流的讀取的方法
http://www.itdecent.cn/p/31ce8caefa25


我們知道java中IO操作是一份很重要的知識點,運用IO知識可以完成許多使用的操作,在Java中,提供了許多方法來進行流的讀寫操作,但是Kotlin 中呢?要怎么寫呢?恰巧今天寫Kotlin頁面的時候遇到了,在Java 中很普通甚至普遍的寫法,在Kotlin 中居然一直是報錯的狀態(tài):

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)會瘋狂提示錯誤! 意思是說參數(shù)是不被允許的,what?怎么會這樣呢,百度了一下,原來Kotlin 中等式不是一個表達式,這種寫法是不被允許的,所有只有選擇其他方法了,后來發(fā)現(xiàn)了Kotlin中的also擴展函數(shù)對,就是這貨,用這貨寫就可以了:

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

所以現(xiàn)在這種就是很好的寫法了,運行起來跟java中的效果是一樣的。
最后,沒事多學(xué)習(xí),有空多掙錢,新的一年,大家繼續(xù)努力

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容