有了扩展函数
,可以在Java类库的基础上扩展出大量“看似Java类中的原生方法”。
Kotlin的标准库 kotlin-stdlib
中大量API都是通过扩展Java类实现的。
Kotlin的原则就是Java已经有的好用的类就直接使用,没有的或者不好用的类,就在原有类的基础上进行功能扩展。
Kotlin为 java.io.File
类扩展了大量好用的扩展函数,同时也针对 Java的 InputStream,OutputStream,Reader
等都做了扩展,相应的代码在 kotlin.io
包下。
读文件
- readText() 函数
- readLines() 函数
- readBytes() 函数
/**
* 获取文件的全部内容,readText() 函数 返回一个字符串;
* 这个函数不适用于大文件,它有2GB的文件大小限制。
*/
fun getFileContent(fileName: String): String {
val f = File(fileName)
return f.readText(Charsets.UTF_8)
}
/**
* 获取文件每行的内容,readLines() 函数 返回一个持有每行内容的列表List
*/
fun getFileLines(fileName: String): List<String> {
val f = File(fileName)
return f.readLines(Charsets.UTF_8)
}
/**
* readBytes() : 读取文件的字节流数组
* 这个函数不适用于大文件,它有2GB的文件大小限制。
*/
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
类。
写文件可以分为一次性写入(覆盖写)和追加写 两种情况。
- writeText() 函数
- appendText() 函数
- appendBytes() 函数
/**
* @param text 要写入文件的内容
* @param destFile 目标文件(带目录)
*
* writeText() 函数,覆盖写文件
*/
fun writeFile(text: String, destFile: String): Unit {
val f = File(destFile)
if (!f.exists()) {
f.createNewFile()
}
// 覆盖写入字符串text
f.writeText(text, Charset.defaultCharset())
}
/**
* @param text 要写入文件的内容
* @param destFile 目标文件(带目录)
*
* appendText() 函数,末尾追加写文件
*/
fun appendFile(text: String, destFile: String): Unit {
val f = File(destFile)
if (!f.exists()) {
f.createNewFile()
}
f.appendText(text, Charset.defaultCharset())
}
/**
* appendBytes() 函数,末尾追加写入 字节数组
*/
fun appendFileBytes(array: ByteArray, destFile: String): Unit {
val f = File(destFile)
if (!f.exists()) {
f.createNewFile()
}
f.appendBytes(array)
}
遍历文件数
walk()
函数
/**
* walk() 函数,遍历指定文件夹下的所有文件
*/
fun traverseFileTree(folderName: String): Unit {
val f = File(folderName)
val fWalk = f.walk()
fWalk.iterator().forEach {
println("${
it.name} ~~~ ${
it.absolutePath}")
}
}
遍历当前文件夹下的所有子目录文件,根据条件进行过滤,把结果存入一个Sequence对象中:
/**
* @param folderName 目标文件夹
* @param p 是一个函数,输入为File类型,输出为Boolean类型的函数
*/
fun getFileSequence(folderName: String, p: (File)->Boolean): Sequence<File> {
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) }
}