Kotlin:获取资源文件夹中所有文件的列表

Mic*_*ael 6 resources classpath kotlin

有没有办法获取 Kotlin 中“资源”文件夹中所有文件的列表?

我可以将特定文件读取为

Application::class.java.getResourceAsStream("/folder/filename.ext")
Run Code Online (Sandbox Code Playgroud)

但有时我只想将文件夹“文件夹”中的所有内容提取到外部目录。

谢谢你。

viv*_*k86 15

由于我在同样的问题上苦苦挣扎并且找不到具体的答案,所以我不得不自己写一个。

这是我的解决方案:

fun getAllFilesInResources()
{
    val projectDirAbsolutePath = Paths.get("").toAbsolutePath().toString()
    val resourcesPath = Paths.get(projectDirAbsolutePath, "/src/main/resources")
    val paths = Files.walk(resourcesPath)
                    .filter { item -> Files.isRegularFile(item) }
                    .filter { item -> item.toString().endsWith(".txt") }
                    .forEach { item -> println("filename: $item") }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我解析了/src/main/resources文件夹中的所有文件,然后仅过滤常规文件(不包括目录),然后过滤 resources 目录中的文本文件。

输出是资源文件夹中所有扩展名为.txt的绝对文件路径的列表。现在您可以使用这些路径将文件复制到外部文件夹。

  • 引用 `"/src/main/resources"` 在捆绑的 JAR 文件中不起作用 (4认同)
  • 当您打包到 jar 时,Java 中的过程是不同的。我想这也适用于 Kotlin。 (3认同)

Dav*_*oko 7

该任务有两个不同的部分:

  1. 获取代表资源目录的文件
  2. 遍历目录

对于1,您可以使用Java的getResource

val dir = File( object {}.javaClass.getResource(directoryPath).file )
Run Code Online (Sandbox Code Playgroud)

对于2,您可以使用 Kotlin 的File.walk扩展函数,该函数返回您可以处理的文件序列,例如:

dir.walk().forEach { f ->
    if(f.isFile) {
        println("file ${f.name}")
    } else {
        println("dir ${f.name}")
    }
}
Run Code Online (Sandbox Code Playgroud)

放在一起你可能会得到以下代码:

val dir = File( object {}.javaClass.getResource(directoryPath).file )
Run Code Online (Sandbox Code Playgroud)

这样如果你有resources/nested目录,你可以:

dir.walk().forEach { f ->
    if(f.isFile) {
        println("file ${f.name}")
    } else {
        println("dir ${f.name}")
    }
}
Run Code Online (Sandbox Code Playgroud)


Zoe*_*Zoe 5

没有方法(即Application::class.java.listFilesInDirectory("/folder/")),但您可以创建自己的系统来列出目录中的文件:

@Throws(IOException::class)
fun getResourceFiles(path: String): List<String> = getResourceAsStream(path).use{
    return if(it == null) emptyList()
    else BufferedReader(InputStreamReader(it)).readLines()
}

private fun getResourceAsStream(resource: String): InputStream? = 
        Thread.currentThread().contextClassLoader.getResourceAsStream(resource) 
                ?: resource::class.java.getResourceAsStream(resource)
Run Code Online (Sandbox Code Playgroud)

然后只需调用getResourceFiles("/folder/"),您将获得文件夹中的文件列表(假设它位于类路径中)。

这是可行的,因为 Kotlin 有一个扩展函数,可以将行读入字符串列表。声明是:

/**
 * Reads this reader content as a list of lines.
 *
 * Do not use this function for huge files.
 */
public fun Reader.readLines(): List<String> {
    val result = arrayListOf<String>()
    forEachLine { result.add(it) }
    return result
}
Run Code Online (Sandbox Code Playgroud)