0

Here, I am reading into console lines from a text file.

I am using BufferedReader and FileReader classes for the purpose.

I am also using the try-with-resources feature of Java 7

To accomplish the same I have the following Java code -

        try (BufferedReader br = new BufferedReader(new FileReader(new File(filePath)))) {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (FileNotFoundException e) {
            System.out.printf("File not found: %s\n", filePath);
            noException = false;
        } catch (IOException e) {
            System.out.printf("File could not be read: %s\n", filePath);
            noException = false;
        }

Now I want to rewrite the same code using Kotlin. I am trying the following approach. But it doesn't seem to be working.

        try(var br: BufferedReader = BufferedReader(FileReader(File(filePath))))

So, how to properly write the code in Kotlin?

Note:

I want to use BufferedReader , FileReader approach only, and not any other approach.

The Kotlin code on which I am trying to apply the try-with-resources feature of Java 7 is -

        var line: String? = ""
        file = File(filePath)
        try {
            fr = FileReader(file)
            br = BufferedReader(fr)
            while (line != null) {
                line = br!!.readLine()
                if (line != null) {
                    sb.append(line).append("\n")
                }
            }
        } catch (e: FileNotFoundException) {
            println("File not found: $filePath")
            noException = false
        } catch (e: IOException) {
            println("File could not be read: $filePath")
            noException = false
        }
        finally {
            try {
                br!!.close()
            } catch (e: IOException) {
                //
                noException = false
            } catch (e: NullPointerException) {
                //
                noException = false
            }
        }

The aim of using try-with-resources feature is to shorten the code

Payel Senapati
  • 1,134
  • 1
  • 11
  • 27

1 Answers1

1

By design, Kotlin doesn't have a language construct akin to try-with-resources in Java.

Instead, we can find an extension method called use in its standard library.

The use keyword can be applied to the above code as follows -

        try {
            val br: BufferedReader = BufferedReader(FileReader(File(filePath)))
            br.use {
                while (line != null) {
                    line = br.readLine()
                    if (line != null) {
                        sb.append(line).append("\n")
                    }
                }
            }
        } catch (e: FileNotFoundException) {
            println("File not found: $filePath")
            noException = false
        } catch (e: IOException) {
            println("File could not be read: $filePath")
            noException = false
        }

The definition of use() in Kotlin, as found in its standard library:

public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R

We can see, in the <T : Closeable?, R> part, that use is defined as an extension function on Java's Closeable interface.

Payel Senapati
  • 1,134
  • 1
  • 11
  • 27
  • Mmm, `use()` is the standard approach for reading and writing files in Kotlin.  (In fact, in many cases you wouldn't even bother with a `try`…`catch` at that, but instead pass it straight up to the caller.) – gidds Sep 11 '20 at 17:05
  • There are further simplifications that can be done: instead of calling `use()` and then `readLine()` in a loop, it'd be better to call `useLines()`; you can call `forEach()` on the result of that, or `map()` or in this case just `joinToString()`.  Also, if I didn't already have a `File` object, I wouldn't bother creating one but would just use the `String` overload of the `FileReader()` constructor. – gidds Sep 11 '20 at 17:09
  • @gidds I am from Java platform complete unaware about Kotlin. My learning path is follow a Java beginners tutorial and translate every Java code to Kotlin code. – Payel Senapati Sep 11 '20 at 18:07
  • That wasn't a criticism, but a pointer to how you could improve your answer :-) – gidds Sep 11 '20 at 19:04