美文网首页
kotlin数据流读取

kotlin数据流读取

作者: kevinsEegets | 来源:发表于2019-10-10 14:18 被阅读0次

最近在用kotlin写一个copy assets文件到sd卡的操作时,发现kotlin下文件写入的神奇之处,特此记录一下

首先感谢大神

https://blog.csdn.net/u011976726/article/details/79125950
https://www.cnblogs.com/shaohz2014/p/3637918.html

作为开发我们都知道在java中Stream代表的是一种数据流或数据源,那对于数据流来说肯定包含输入流和输出流
java中的输入流我们叫InputStream, 输出流当然就是OutputStream, 对于数据流来说我们肯定要读取,那么java对封装单位通用方法就是read() 方法了。

java中读取数据流:

#### java 代码
void readStream(InputStream input, OutputStream output) throws IOException {
 byte[] buffer = new byte[1024];
 int nread;  
 while ((nread = input.read(buffer)) != -1) {
    if (nread == 0) {
        nread = input.read();
        if (nread < 0)
            break;
        output.write(nread);
        continue;
    }
    output.write(buffer, 0, nread);
        }
}

kotlin代码

/*
 *  Usually
 */
@Throws(IOException::class)
fun wirteStreamFun2(`in`: InputStream, output: OutputStream){
    var uread: Int = `in`.read()
    `in`.use { `input` ->
        output.use {
            while (uread != -1){
                it.write(uread)
                uread = input.read()
            }
        }
    }
}
/*
 * Better
 */
@Throws(IOException::class)
fun writeStreamFun1(`in`: InputStream, output: OutputStream){
    var uread: Int = -1
    `in`.use { `input` ->
       output.use {
           val result = {uread = input.read(); uread}
           //栗子  val aMethod = { print(""); 1}    val aMethod = { Int_A = Int_B; Int_C} as Int_C
           while(result() != -1){
               it.write(uread)
           }
       }
    }
}
/*
 * Unbelievable
 */
@Throws(IOException::class)
fun witteStreamFun3(`in`: InputStream, output: OutputStream){
    var uread: Int = -1
    `in`.use{ `input` ->
        output.use {
            while(input.read().also { uread = it } != -1){
                it.write(uread)
            }
        }
    }
}

kotlin 给我们提供了更为简洁的写法,如下

/*
* Kotlin IO
 */
fun wirteStreamKt(`in`: InputStream, output: OutputStream, bufferSize: Int){
    `in`.copyTo(output, bufferSize)
}

copyTo源码如下

/**
 * Copies this stream to the given output stream, returning the number of bytes copied
 *
 * **Note** It is the caller's responsibility to close both of these resources.
 */
public fun InputStream.copyTo(out: OutputStream, bufferSize: Int = DEFAULT_BUFFER_SIZE): Long {
    var bytesCopied: Long = 0
    val buffer = ByteArray(bufferSize)
    var bytes = read(buffer)
    while (bytes >= 0) {
        out.write(buffer, 0, bytes)
        bytesCopied += bytes
        bytes = read(buffer)
    }
    return bytesCopied
}

我们可以清楚的看到kotlin 对于字节流的读写给我们做了二次封装。
对于kotlin更多关于数据流的操作,可以了解 org.jetbrains.kotlin.kotlin-stadlib:1..3.40 新特性或者可以看大神的文章

https://www.jianshu.com/p/9eef6b526375

相关文章

网友评论

      本文标题:kotlin数据流读取

      本文链接:https://www.haomeiwen.com/subject/nauructx.html