使用BufferedReader和FileReader将文本文件中的行读入控制台,并在Kotlin中应用try-with-resources

问题描述

在这里,我正在从文本文件中读取控制台行。

我正在为此目的使用BufferedReaderFileReader 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中正确编写代码

注意:

我只想使用BufferedReaderFileReader方法,而不要使用任何其他方法

我尝试在其上应用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()的定义(在其标准库中找到):

公共内联乐趣 T.use(块:(T)-> R):R

部分中,我们看到使用被定义为Java的Closeable接口上的扩展功能。