Kotlin文件IO操作与多线程
IO操作
// 在原有基础上扩展函数主要有一下几个:
Kotlin/io/files/FileTreeWalk.kt
kotlin/io/files/Utils.kt
kotlin/io/files/FileReadWrite.kt
kotlin/io/IOStreams.kt
kotlin/io/ReadWrite.kt
- 读文件(readText、readLines、readBytes)
/**
* 获取文件全部内容字符串
*/
fun getFileContent(fileName: String): String {
val f = File(fileName)
return f.readText(Charset.forName("UTF-8"))
}
- 写文件(writeText、appendText)
/**
* 把文本写入文件中
*/
fun writeFile(text: String, destFile: String) {
val f = File(destFile)
if (!f.exists()) {
f.createNewFile()
}
f.writeText(text, Charset.defaultCharset())
}
- 网络IO操作
/**
* 根据url获取该url的HTML函数
*/
fun getUrlContent(url: String): String {
return URL(url).readText(Charset.defaultCharset())
}
/**
* 根据url获取该url响应的比特数组函数
*/
fun getUrlBytes(url: String): ByteArray {
return URL(url).readBytes()
}
/**
* 把url响应字节数组写入文件
*/
fun writeBytesTo(fileName: String, url: String) {
val bytes = URL(url).readBytes()
File(fileName).writeBytes(bytes)
}
正则表达式
Kotlin中依然可用Java中的Pattern、Matcher等类,还提供了一个正则表达式类kotlin/text/regex/Regex.kt,可通过Regex的构造函数创建一个正则表达式。
- 构造Regex表达式
// (1)使用构造函数
val r1 = Regex("[a-z]+")
// (2)使用String的toRegex扩展函数
val r2= "[a-z]+".toRegex()
- 使用
val r1 = Regex("[a-z]+")
// 字符串全匹配
val matches = r1.matches(input = "abcd") // true
// 字符串至少有一个匹配
val containsMatchIn = r1.containsMatchIn(input = "12311") //false
// 替换字符串中匹配的内容
val replace = r1.replace(input = "123sdsf", replacement = "acd") //123acd
多线程
Kotlin 中没有synchronized和volatile关键字,虽然Any类似于Java的Object,但是也没有wait()、notify()和notifyAll()方法。
- 三种创建线程方式
// (1)使用对象表达式创建
object : Thread() {
override fun run() {
Thread.sleep(3000)
println("使用Thread对象表达式:${Thread.currentThread()}")
}
}.start()
// (2)使用Lambda表达式
Thread ({
Thread.sleep(3000)
println("使用Lambda表达式:${Thread.currentThread()}")
}).start()
// (3)使用Kotlin封装的thread函数
thread(start = true,isDaemon = false,name = "DThread",priority = 3){
Thread.sleep(3000)
println("使用Kotlin封装的函数thread():${Thread.currentThread()}")
}
thread {
Thread.sleep(3000)
println("使用Kotlin封装的函数thread():${Thread.currentThread()}")
}
// 使用Lambda表达式:Thread[Thread-1,5,main]
// 使用Thread对象表达式:Thread[Thread-0,5,main]
// 使用Kotlin封装的函数thread():Thread[DThread,3,main]
// 使用Kotlin封装的函数thread():Thread[Thread-3,5,main]
- 同步方法和块
@Synchronized注解和Java中的synchronized效果相同:它会将JVM方法标记为同步。同步块使用synchronize()函数。
@Synchronized fun appendFile(text:String,destFile: String){
val f= File(destFile)
if (!f.exists()){
f.createNewFile()
}
f.appendText(text, Charset.defaultCharset())
}
class Sync{
fun appenFileSync(text: String, destFile: String) {
val f = File(destFile)
if (!f.exists()) {
f.createNewFile()
}
synchronized(this) {
f.appendText(text, Charset.defaultCharset())
}
}
}
- 可变字段
Kotlin中有更好用的协程并发库,在实际使用中,择情况使用。
@Volatile
private var running = false
fun start() {
running = true
thread(start = true) {
while (running) {
println("still running:${Thread.currentThread()}")
}
}
}
fun stop() {
running = false
println("stoped: ${Thread.currentThread()}")
}