这里,我正在从一个文本文件中读取控制台行。
我使用的是BufferedReader
和FileReader
classes
。
我也在使用Java 7 的try-with-resources
功能
为了实现同样的目的,我有以下Java代码-
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: %sn", filePath);
noException = false;
} catch (IOException e) {
System.out.printf("File could not be read: %sn", filePath);
noException = false;
}
现在我想用Kotlin重写相同的代码。我正在尝试以下方法。但它似乎不起作用。
try(var br: BufferedReader = BufferedReader(FileReader(File(filePath))))
那么,如何在Kotlin中正确地编写代码呢?
注:
我只想使用BufferedReader
、FileReader
方法,而不想使用任何其他方法。
我尝试应用Java7的try-with-resources
特性的Kotlin代码是-
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
}
}
使用try-with-resources
功能的目的是缩短代码
根据设计,Kotlin没有类似于Java中try-with-resources
的语言构造。
相反,我们可以在其标准库中找到一个名为use
的扩展方法。
use
关键字可以应用于以上代码,如下所示-
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
}
Kotlin中use()
的定义,见其标准库:
公共内联娱乐<T:可关闭?,R>T.use(块:(T(->R( :R
我们可以在<T:可关闭?,R>部分,该用途被定义为Java的Closeable接口上的扩展函数。