What I have to do at 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();
}
But kotlin doesn't know about try-with-resources! So my code is
try {
val input = FileInputStream("/home/user/123.txt")
} finally {
// but finally scope doesn't see the scope of try!
}
Is there an easy way to close the stream ? And I don't speak only about files. Is there a way to close any stream easily ?
InputStreamReader will not close an interface. It will close the underlying data resource (like file descriptor) if it is. It will do nothing if close is override and empty in an implementation.
It's important to close any resource that you use. in. close will close BufferedReader, which in turn closes the resources that it itself uses ie. the InputStreamReader.
Provides an interface to a file system and is the factory for objects to access files and other objects in the file system.
Creates an input stream for reading data from this byte array. Creates an input stream for reading data from the specified portion of this byte array.
Closeable.use is what you're looking for:
val result = FileInputStream("/home/user/123.txt").use { input ->
//Transform input to X
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With