`

[Kotlin]如何关闭stream

阅读更多

众所周知,在java中,在finally代码块中可以使用close()关闭不使用的stream。当然kotlin也可以沿用这种操作,那是否有更简单的操作呢?答案是肯定的。

 

Closeable.use,只要继承了Closeable的类,都可以使用。通过看use的源码,可以看到最后会调用close方法。

因此只需要这样使用:

BufferedWriter(OutputStreamWriter(out)).use {
            it.write(inputText)
        }

 把需要执行的动作放在block中,执行完后,自动会关闭BufferedWriter的流

 

参考:

1.https://stackoverflow.com/questions/46098105/is-there-a-way-to-open-and-close-a-stream-easily-at-kotlin/46098204?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

2.https://stackoverflow.com/questions/26969800/try-with-resources-in-kotlin

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics