gpt4 book ai didi

java - 有没有办法在 kotlin 轻松打开和关闭流?

转载 作者:IT老高 更新时间:2023-10-28 13:46:29 25 4
gpt4 key购买 nike

我在 java 要做的事:

try(InputStream inputStream = new FileInputStream("/home/user/123.txt")) {

byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
System.out.println(new String(bytes));


} catch (IOException e) {
e.printStackTrace();
}

但是 kotlin 不知道 try-with-resources!所以我的代码是

try {
val input = FileInputStream("/home/user/123.txt")
} finally {
// but finally scope doesn't see the scope of try!
}

有没有简单的方法来关闭流?而且我不仅仅谈论文件。有没有办法轻松关闭任何 stream

最佳答案

Closeable.use就是你要找的东西:

val result = FileInputStream("/home/user/123.txt").use { input ->
//Transform input to X
}

关于java - 有没有办法在 kotlin 轻松打开和关闭流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46098105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com