一、文件I/O操作
参考《Kotlin从入门到进阶实战》114页
二、网络I/O
参考《Kotlin从入门到进阶实战》118页
三、执行Shell命令
参考《Kotlin从入门到进阶实战》119页
四、正则表达式
1、构造Regex表达式
使用Regex构造函数如下:
// 正则表达式
val r1 = Regex("[a-z]+") //创建一个Regex对象,匹配的正则表达式是[a-z]+
val r2 = Regex("a-z+",RegexOption.IGNORE_CASE)
var r3 = "[A-Z]+".toRegex() // 直接使用Kotlin中给String扩展的toRegex
2、Regex函数
参考《Kotlin从入门到进阶实战》120页
五、多线程编程
1、创建线程
1)使用对象表达式创建(相当于java中集成Thread类)
// 多线程
object : Thread() { // object对象表达式
override fun run() {
super.run()
sleep(300)
println("Thread : A 使用 Thread 对象表达式: ${Thread.currentThread()}")
}
}.start()
// 输出
I/System.out: Thread : A 使用 Thread 对象表达式: Thread[Thread-2,5,main]
2) 使用lambda表达式创建
Thread( {
Thread.sleep(300)
println("Thread : B 使用 Thread 对象表达式: ${Thread.currentThread()}")
}).start()
在这里看不到Runnable,在Kotlin中可以直接使用上面的Lambda表达式来表示。
3)使用kotlin封装的Thread()函数
val t = Thread({
Thread.sleep(2000)
println("Thread : C 使用 Thread 对象表达式: ${Thread.currentThread()}")
})
t.isDaemon = false
t.name="CThread"
t.priority = 3
t.start()
后面的四行式样板化的代码,在kotlin中把这样的操作封装简单化:
thread(start = true, isDaemon = false,name = "DThread",priority = 4) {
Thread.sleep(2000)
println("Thread : D 使用 Thread 对象表达式: ${Thread.currentThread()}")
}
2、同步方法和块
synchronized不是kotlin中的关键字,它替换为@synchronized注解。
// 同步方法
@Synchronized fun appendFile(text : String ,destFile : String) {
val f = File(destFile)
if (f.exists()) {
f.createNewFile()
}
f.appendText(text, Charset.defaultCharset())
}
// 同步代码块
fun appendFile(text : String ,destFile : String) {
val f = File(destFile)
if (f.exists()) {
f.createNewFile()
}
synchronized(this) {
f.appendText(text, Charset.defaultCharset())
}
}
3、可变字段
kotlin中没有volatile字段,但是有@Volatile注解
@Volatile private var running = false
fun start () {
running = true
thread (start = true){
while (running) {
println("Thread : D 使用 Thread 对象表达式: ${Thread.currentThread()}")
}
}
}