轉(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ù)努力