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