使用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功能的目的是缩短代码

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)