Kotlin file IO operations and multithreading
IO operation
// 在原有基础上扩展函数主要有一下几个:
Kotlin/io/files/FileTreeWalk.kt
kotlin/io/files/Utils.kt
kotlin/io/files/FileReadWrite.kt
kotlin/io/IOStreams.kt
kotlin/io/ReadWrite.kt
- Read files (readText, readLines, readBytes)
/**
* 获取文件全部内容字符串
*/
fun getFileContent(fileName: String): String {
val f = File(fileName)
return f.readText(Charset.forName("UTF-8"))
}
- Write file (writeText, appendText)
/**
* 把文本写入文件中
*/
fun writeFile(text: String, destFile: String) {
val f = File(destFile)
if (!f.exists()) {
f.createNewFile()
}
f.writeText(text, Charset.defaultCharset())
}
- Network IO operation
/**
* 根据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)
}
regular expression
Pattern, Matcher and other classes in Java are still available in Kotlin, and a regular expression class kotlin/text/regex/Regex.kt is also provided, which can create a regular expression through the constructor of Regex.
- Constructing a Regex expression
// (1)使用构造函数
val r1 = Regex("[a-z]+")
// (2)使用String的toRegex扩展函数
val r2= "[a-z]+".toRegex()
- use
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
Multithreading
There are no synchronized and volatile keywords in Kotlin. Although Any is similar to Java's Object, there are no wait(), notify() and notifyAll() methods.
- Three ways to create threads
// (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 methods and blocks
The @Synchronized annotation has the same effect as synchronized in Java: it marks the JVM method as synchronized. Synchronized blocks use the synchronize() function.
@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())
}
}
}
- variable field
There are better coroutine concurrency libraries in Kotlin, and in actual use, choose the situation to use.
@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()}")
}