Kotlin 文件IO

Kotlin 文件IO,第1张

Kotlin 文件IO

有了扩展函数,可以在Java类库的基础上扩展出大量“看似Java类中的原生方法”。
Kotlin的标准库 kotlin-stdlib 中大量API都是通过扩展Java类实现的。

Kotlin的原则就是Java已经有的好用的类就直接使用,没有的或者不好用的类,就在原有类的基础上进行功能扩展。
Kotlin为 java.io.File 类扩展了大量好用的扩展函数,同时也针对 Java的 InputStream,OutputStream,Reader 等都做了扩展,相应的代码在 kotlin.io 包下。

读文件
  1. readText() 函数
  2. readLines() 函数
  3. readBytes() 函数
fun getFileContent(fileName: String): String {
    val f = File(fileName)
    return f.readText(Charsets.UTF_8)
}


fun getFileLines(fileName: String): List {
    val f = File(fileName)
    return f.readLines(Charsets.UTF_8)
}
fun getFileBytes(fileName: String): Unit {
    val f = File(fileName)
    val bytes = f.readBytes()
    val content = bytes.joinToString(separator = "_")
    println("readBytes: ")
    println(content)
}
写文件

与读文件类似,可以写入字符串,也可以写入字节流,还可以调用Java的 Writer、OutputStream 类。
写文件可以分为一次性写入(覆盖写)和追加写 两种情况。

  1. writeText() 函数
  2. appendText() 函数
  3. appendBytes() 函数
fun writeFile(text: String, destFile: String): Unit {
    val f = File(destFile)
    if (!f.exists()) {
        f.createNewFile()
    }
    // 覆盖写入字符串text
    f.writeText(text, Charset.defaultCharset())
}
fun appendFile(text: String, destFile: String): Unit {
    val f = File(destFile)
    if (!f.exists()) {
        f.createNewFile()
    }
    f.appendText(text, Charset.defaultCharset())
}
fun appendFileBytes(array: ByteArray, destFile: String): Unit {
    val f = File(destFile)
    if (!f.exists()) {
        f.createNewFile()
    }
    f.appendBytes(array)
}
遍历文件数

walk() 函数

fun traverseFileTree(folderName: String): Unit {
    val f = File(folderName)
    val fWalk = f.walk()
    fWalk.iterator().forEach {
        println("${it.name} ~~~ ${it.absolutePath}")
    }
}

遍历当前文件夹下的所有子目录文件,根据条件进行过滤,把结果存入一个Sequence对象中:

fun getFileSequence(folderName: String, p: (File)->Boolean): Sequence {
    val f = File(folderName)
    val fWalk = f.walk()
    return fWalk.filter(p)
}

fun testFileSequence(): Unit {
    val folder = "."
//    val p = fun(f:File)  = run { f.name.endsWith(".kt") }
    val sequence = getFileSequence(folder) { file -> file.isFile }
    sequence.iterator().forEach { println(it.absolutePath) }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5693561.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存