Kotlin Io流与序列化,小结
发表于更新于
广州
开发KotlinKotlin Io流与序列化,小结
❄️2winter在Kotlin中IO库基本分为两类:
字符输入输出流:Reader,Writer |负责对char的处理
字节输入输出流:InputStream,OutputStream | 负责对byte的处理
链接机制:流处理器之间可以相互关联起来,其中一个的输出作为另一个的输入。
1.输入输出流结构
InputStream原始处理器下的链接处理器:
- ByteArrayInputStream
- FileInputStream
- ObjectInputStream
- StringBufferInputStream
- …
OutputStream原始处理器下的链接处理器:
- ByteArrayOutputStream
- FileOutputStream
- ObjectOutputStream
- …
2.下面是读写结构
Reader:
- BufferedReader
- CharArrayReader
- InputStreamReader
- StringReader
- …
Weiter:
- BufferedWriter
- CharArrayReader
- OutputStreamWriter
- PrintWriter
- 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() } } }
|
序列化与反序列化
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() } 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
|
❄️2winter
ReactNative FullStack Developer
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 ❄️2winter!