Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to open and close a stream easily at kotlin? [duplicate]

Tags:

java

kotlin

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 ?

like image 313
faoxis Avatar asked Sep 07 '17 13:09

faoxis


People also ask

Does InputStreamReader close underlying stream?

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.

Do I need to close InputStreamReader?

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.

What is closeable Kotlin?

Provides an interface to a file system and is the factory for objects to access files and other objects in the file system.

What is kotlin Inputstream?

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.


1 Answers

Closeable.use is what you're looking for:

val result = FileInputStream("/home/user/123.txt").use { input ->
    //Transform input to X
}
like image 173
Kiskae Avatar answered Nov 06 '22 00:11

Kiskae