如何在Kotlin,Gradle的resources文件夹中创建文件

ymdaylpp  于 2023-02-13  发布在  Kotlin
关注(0)|答案(2)|浏览(263)

在一个全新的项目中,我希望在运行时在src/main/resources/文件夹中创建一个文件myFile.json
为了阅读一个文件,我需要在build.gradle.kts文件中做一些配置,但是我找不到任何关于如何创建文件的信息。

uemypmqf

uemypmqf1#

假设目录src/main/resources/存在:

val f = File("src/main/resources/myFile.json")
withContext(Dispatchers.IO) {
    f.createNewFile()  // This is the answer to the question
    f.printWriter().use { out ->
        out.println("{}")
    }
}
h43kikqp

h43kikqp2#

1.@Endzeit问到目前为止你都尝试了什么,请分享代码。
1.就像@cyberbrain说的-你确定要写到资源文件夹吗?
下面是写回源资源文件夹所在位置的代码:

fun main(args: Array<String>) {
    // Let's assume you want your project to be portable, so you don't
    // want to use absolute file paths.
    // Find out where your IDE will launch the project from.  Normally this is
    // the root folder of the whole project.  Find out with this: the `canonicalPath` will help:
    val workingFolder = File(".")
    println("workingFolder=${workingFolder.canonicalPath}")

    // Define the folder you want to write in to
    // this will vary especially if you have a nested project structure
    // IntelliJ under the Edit > Copy Path menu option will help you find the resources
    // relative location
    val parentFolder = File("src/main/resources")
    println("parentFolder=${parentFolder.canonicalPath}")
    require(parentFolder.exists())
    val outFile = File(parentFolder, "test.txt")
    outFile.printWriter(StandardCharsets.UTF_8).use {
        it.println("Hello world")
    }
    println("Wrote to ${outFile.canonicalPath}")
}

相关问题