/**基于java.io，并对其进行了一些扩展
 * 1）扩展了基本的read/write方法，会自动关闭流
 * 2) 提供了主要流及文件之间的转换操作
 * 3）新增了文件夹遍历的方法
 */
import java.io.*
import java.net.URL
import java.nio.charset.Charset
fun main(){
    //终端IO
    val line = readLine()
    println(line)

    //网络IO
    val rt = URL("https://blog.csdn.net/xotty").readText()
    println(rt)
    val rb = URL("https://avatar.csdnimg.cn/F/5/A/2_xotty.jpg").readBytes()
    println(rb)

    //文件IO
    val currentPath=System.getProperty("user.dir")
    val file =File("src/database.kt")
    readFile(file)

    val newFilePath=currentPath +"/out"
    val newFile = File(newFilePath, "newfile.txt")
    writeFile(newFile)

    traverseFileTree(currentPath)
}

fun readFile(file:File) {
    //方法1：readText，一次读取整个文件到String
    val contents = file.readText(Charset.forName("utf-8"))
    println(contents)

    //方法2：readLine，一次读取一行文件到List<String>
    file.readLines().forEach(::println)
    file.readLines().take(3).forEach {
        println(it.toUpperCase())
    }

    //方法3：BufferReader
    BufferedReader(FileReader(file)).use {
        var line: String
        while(true){
            line = it.readLine()?:break
            println(line)
        }
    }

    with(file.reader()) {
        val br = BufferedReader(this)
        var text = br.readLine()
        while (text != null) {
            println(text)
            text = br.readLine()
        }
        this.close()
        br.close()
    }

    //方法4：forEachLine
    file.forEachLine(Charsets.UTF_8) { println(it) }
    file.forEachLine(action = ::println)

    //读取为bytes,一次读取整个文件到ByteArray
    var bytes: ByteArray = file.readBytes()
    println(bytes.joinToString(separator = " "))
    println("---------------------")
    //读取为bytes,一次读取指定字节数到ByteArray
    val stream = file.inputStream()
    bytes = ByteArray(16)
    while(stream.read(bytes)>0)  println(bytes.toString(Charsets.UTF_8))
    stream.close()

}

fun writeFile(file:File) {
    file.writeText("Hello world!")
    println(file.readText())
    file.appendText("We are family!")
    println(file.readText())

    with(file.writer()) {
        BufferedWriter(this).apply {
            write("addText")
            close()
            this@with.close()
        }
    }
    println(file.readText())

    file.writeBytes(byteArrayOf(52, 56, 83, 57))
    println(file.readText())
    file.appendBytes(byteArrayOf(98, 85, 74, 93))
    println(file.readText())
    val mfile=File(file.getParent(),"data.txt")
    if (mfile.exists()) mfile.delete()
    file.copyTo(mfile)
}

fun traverseFileTree(path:String) {
    val rootDir = File(path)
    val fileTree: FileTreeWalk = rootDir.walk()
        fileTree.forEach { println(it) }

        println("Kotlin source code file:")
        fileTree.maxDepth(3)
        .filter { it.isFile }
        .filter { it.extension == "kt" }
        .forEach(::println)
}