【问题标题】:Not able to write Message into file using Kotlin无法使用 Kotlin 将消息写入文件
【发布时间】:2018-12-30 01:21:33
【问题描述】:

我在我的项目中使用 kotlin 语言。我使用了下面的代码,代码没有抛出任何错误,但我在日志消息中收到了 file not found 异常。

var a="Hello"

WriteToFile(a)

    fun WriteToFile(message: String)
    {
        try {
            var writer=FileWriter("message.txt")
            writer.write(message)
            writer.close()
        }
        catch (ex: Exception)
        {
            println("Exception $ex")
        }
    }

错误

 Caused by: java.io.FileNotFoundException: message.txt (No such file or directory)

【问题讨论】:

  • 你是否在Manifest.xml中添加了权限``?
  • 在 write.close() 之前也要执行 writer.flush()
  • @ankuranurag2 我是 Kotlin 的新手,但是在许多语言中,当调用析构函数时缓冲区会刷新,在 Kotlin 中不也是这种情况吗?我的意思是,当我们调用writer.close() 时,缓冲区会在关闭前自动刷新

标签: android file android-studio kotlin


【解决方案1】:

您的代码工作正常,也许它没有在当前目录中创建文件的权限,您可以指定一个您知道的绝对位置以确保它可以工作。另外作为建议,如果您的目标是 JVM,您可以使用 use 函数。

示例

fun main() = runBlocking {
    writeToFile("Hello, World!!!")
}

fun writeToFile(message: String) {
    FileWriter("/Users/omainegra/Desktop/message.txt").use { writer ->
        try {
            writer.write(message)
        }
        catch (ex: Exception) {
            ex.printStackTrace()
        }
    }
}

输出

另外,我想提一下,如果您只需要在文件中写入String,使用File("message.txt").writeText(message)即可轻松完成

【讨论】:

  • 感谢@Omar 的评论,但我仍然遇到同样的错误。我正在使用 Windows,所以我需要在我的路径中将 / 更改为 \ 吗?
  • java.nio.Files 是一个更好的选择;见java7fs.wikia.com/wiki/Why_File_sucks
猜你喜欢
  • 2023-03-19
  • 1970-01-01
  • 2019-01-08
  • 2018-06-20
  • 2018-09-19
  • 2016-08-27
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多