无法使用Kotlin将消息写入文件

用户名

我在项目中使用Kotlin语言。我在下面的代码中使用了代码,但代码没有抛出错误,但是我在日志消息中发现文件未找到异常。

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)
奥马尔·缅因格拉

您的代码可以正常工作,也许它没有权限在当前目录中创建文件,您可以指定一个绝对位置,以确保它可以正常工作。另外建议,如果您以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写入,则可以轻松完成File("message.txt").writeText(message)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章