Kotlin Io流与序列化,小结

  |   0 评论   |   0 浏览

在Kotlin中IO库基本分为两类:

字符输入输出流:Reader,Writer |负责对char的处理

字节输入输出流:InputStream,OutputStream | 负责对byte的处理

链接机制:流处理器之间可以相互关联起来,其中一个的输出作为另一个的输入。

1.输入输出流结构

InputStream原始处理器下的链接处理器:

  1. ByteArrayInputStream
  2. FileInputStream
  3. ObjectInputStream
  4. StringBufferInputStream
  5. ...

OutputStream原始处理器下的链接处理器:

  1. ByteArrayOutputStream
  2. FileOutputStream
  3. ObjectOutputStream
  4. ...

2.下面是读写结构

Reader:

  1. BufferedReader
  2. CharArrayReader
  3. InputStreamReader
  4. StringReader
  5. ...

Weiter:

  1. BufferedWriter
  2. CharArrayReader
  3. OutputStreamWriter
  4. PrintWriter
  5. StringWriter
  6. ...

读取文件与写入文件:

//写入
fun fwr(path: String) {
    with(File(path).writer()) {
        BufferedWriter(this).apply {
            this.write("addText")
            close()
            this@with.close()
        }
    }

}
//读取
fun fre(path: String) {
    with(File(path).reader()) {
        val br = BufferedReader(this)
        var text = br.readLine()
        while (text != null) {
            println(text)
            text = br.readLine()
            this.close()
            br.close()
        }
    }
}

null

序列化与反序列化

/**
 * 序列化
 */
fun seriza(needString: String) {

    val f = File(needString)
    if (!f.exists()) {
        f.createNewFile()
    }
    //打开f文件输出流
    val fStream = FileOutputStream(f)
    try {
        ObjectOutputStream(fStream).apply {
            writeObject(Iwh("li", "19"))
            close()
        }
    } catch (e: Exception) {
        println(e.toString())
    } finally {
        fStream.close()
    }
}

/**
 * 反序列化
 */
fun unseriza(s: String): Iwh? {
    val f = FileInputStream(s)
    var objectIwh: Iwh? = null

    ObjectInputStream(f).apply {
        objectIwh = this.readObject() as Iwh
        println("反序列化:${objectIwh!!.age}")
    }
    return objectIwh
}

class Iwh(val nam: String, val age: String) : Serializable

null


标题:Kotlin Io流与序列化,小结
作者:yf_d
地址:看看我的CSDN