Kotlin Io流与序列化,小结

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

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

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

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

1.输入输出流结构

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

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

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

  1. ByteArrayOutputStream
  2. FileOutputStream
  3. ObjectOutputStream

2.下面是读写结构

Reader:

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

Weiter:

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

读取文件与写入文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//写入
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

序列化与反序列化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* 序列化
*/
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