Kotlin learning notes (IV) - file IO operation and multithreading

Kotlin file IO operation and multithreading

IO operation

// On the basis of the original extension functions, there are mainly the following:
Kotlin/io/files/FileTreeWalk.kt
kotlin/io/files/Utils.kt
kotlin/io/files/FileReadWrite.kt

kotlin/io/IOStreams.kt
kotlin/io/ReadWrite.kt
  1. Read files (readText, readLines, readBytes)
/**
 * Get all content strings of the file
 */
fun getFileContent(fileName: String): String {
    val f = File(fileName)
    return f.readText(Charset.forName("UTF-8"))
}
  1. Write files (writeText, appendText)
/**
 * Write text to file
 */
fun writeFile(text: String, destFile: String) {
    val f = File(destFile)
    if (!f.exists()) {
        f.createNewFile()
    }
    f.writeText(text, Charset.defaultCharset())
}
  1. Network IO operation
/**
 * Get the HTML function of the url according to the url
 */
fun getUrlContent(url: String): String {
    return URL(url).readText(Charset.defaultCharset())
}

/**
 * Get the bit array function of the url response according to the url
 */
fun getUrlBytes(url: String): ByteArray {
    return URL(url).readBytes()
}

/**
 * Write url response byte array to file
 */
fun writeBytesTo(fileName: String, url: String) {
    val bytes = URL(url).readBytes()
    File(fileName).writeBytes(bytes)
}

regular expression

Kotlin can still use Java's Pattern, Matcher and other classes. It also provides a regular expression class kotlin/text/regex/Regex.kt, which can create a regular expression through Regex's constructor.

  1. Construct Regex expression
// (1) Using constructors
val r1 = Regex("[a-z]+")

// (2) Using the tregex extension function of String
val r2= "[a-z]+".toRegex()
  1. Use
val r1 = Regex("[a-z]+")

// String full match
val matches = r1.matches(input = "abcd") // true

// String has at least one match
val containsMatchIn = r1.containsMatchIn(input = "12311") //false

// Replace matching content in string
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 Object, there are no wait(), notify(), and notifyAll() methods.

  1. Three ways to create threads
    // (1) Creating with object expressions
    object : Thread() {
        override fun run() {
            Thread.sleep(3000)
            println("Use Thread Object expression:${Thread.currentThread()}")
        }
    }.start()

    // (2) Using Lambda expressions
    Thread ({
        Thread.sleep(3000)
        println("Use Lambda Expression:${Thread.currentThread()}")
    }).start()

    // (3) thread function encapsulated with Kotlin
    thread(start = true,isDaemon = false,name = "DThread",priority = 3){
        Thread.sleep(3000)
        println("Use Kotlin Encapsulated functions thread():${Thread.currentThread()}")
    }

    thread {
        Thread.sleep(3000)
        println("Use Kotlin Encapsulated functions thread():${Thread.currentThread()}")
    }

//    Using Lambda expressions: Thread[Thread-1,5,main]
//    Use Thread object expression: Thread[Thread-0,5,main]
//    thread():Thread[DThread,3,main] encapsulated with Kotlin
//    Thread(), a Kotlin encapsulated function: thread [thread-3,5, main]
  1. Synchronization methods and blocks

@The synchronized annotation has the same effect as synchronized in Java: it marks the JVM method as synchronized. Synchronization 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())
        }
    }
}


  1. Variable field

In Kotlin, there is a better concurrency library for collaboration. In actual use, it can be used according to the situation.
@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()}")
}

Keywords: Lambda Java network jvm

Added by johnnycsh on Mon, 30 Mar 2020 18:48:05 +0300