我在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();
}
Run Code Online (Sandbox Code Playgroud)
但kotlin不知道try-with-resources!所以我的代码是
try {
val input = FileInputStream("/home/user/123.txt")
} finally {
// but finally scope doesn't see the scope of try!
}
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法来关闭流?我不会只谈论文件.有没有办法stream轻松关闭?
Kis*_*kae 15
Closeable.use 正是你要找的:
val result = FileInputStream("/home/user/123.txt").use { input ->
//Transform input to X
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2741 次 |
| 最近记录: |