8

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 ?

faoxis
  • 1,912
  • 5
  • 16
  • 31

2 Answers2

37

Closeable.use is what you're looking for:

val result = FileInputStream("/home/user/123.txt").use { input ->
    //Transform input to X
}
Kiskae
  • 24,655
  • 2
  • 77
  • 74
-4
 BufferedInputStream input = null;
        try {
            input = new BufferedInputStream(new FileInputStream("/home/user/123.txt"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                input.close();
            }
        }

Works fine with any Inputstream. This is just an example i used.

Didi
  • 29
  • 5