有没有办法在kotlin轻松打开和关闭流?
在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 }
标准库为您的用例提供了use
方法。 它可以在Closable
(作为扩展实现)( AutoClosable
的基类)上调用。 每个普通的Stream
实现其中的一个,因此它就是你所需要的。
FileInputStream("name").use{ // whatever you like }
传递use
的代码将被执行, close()
(可close()
合约)将在之后被执行。
BufferedInputStream input = null; try { input = new BufferedInputStream(new FileInputStream("/home/user/123.txt")); } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { input.close(); } }
适用于任何Inputstream。 这只是我使用的一个例子。