问题描述
我正在为此目的使用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: %s\n",filePath);
noException = false;
} catch (IOException e) {
System.out.printf("File Could not be read: %s\n",filePath);
noException = false;
}
现在,我想使用Kotlin重写相同的代码。我正在尝试以下方法。但这似乎不起作用。
try(var br: BufferedReader = BufferedReader(FileReader(File(filePath))))
那么,如何在Kotlin中正确编写代码?
注意:
我只想使用BufferedReader
,FileReader
方法,而不要使用任何其他方法。
我尝试在其上应用Java 7的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()
的定义(在其标准库中找到):
公共内联乐趣
在