文件IO,正則和多線程
得益于kotlin的擴展函數(shù)衣屏,kotlin對java中api進行了改進躏升,對于java中好用的api直接使用,對于不好用的api進行了擴展和改進狼忱。
1 文件IO操作
讀寫
fun main() {
val f = File("test.txt")
// 寫入文件
f.writeText("hello kotlin") // 默認為utf-8,覆蓋寫
f.appendBytes(ByteArray(1).apply { this[0] = '\n'.toByte() }) // 追加一個字節(jié)
f.appendText("hello io") // 追加字符串
// 讀取文本中所有數(shù)據(jù)
val s = f.readText() // 默認為utf-8
val ss = f.readLines() // 返回 List<String> 類型
val bs = f.readBytes() // 返回 ByteArray 相當于Java中的 Byte[]
// 分塊讀取數(shù)據(jù)
val buffer = f.bufferedReader()
while(true){
val line = buffer.readLine()
if(line == null) break
else println(line)
}
}
編碼格式默認選擇utf-8
分塊寫入數(shù)據(jù)
fun main() {
val f = File("test2.txt")
val writer = f.bufferedWriter()
writer.appendln("line 1")
writer.newLine()
writer.appendln("line 2")
//writer.flush()
writer.close()
}
這里最好使用flush或者close膨疏,否則數(shù)據(jù)可能停留在緩沖區(qū)
遍歷文件夾
fun main() {
val f = File("E:\\課件\\")
val walk = f.walk()
walk.forEach { println(it.absoluteFile) } // 遞歸打印所有文件
println("-------------分隔符---------------")
val filter =walk.filter { it -> it.name.contains("網(wǎng)絡(luò)安全") }
filter.iterator().forEach { println(it.absoluteFile) }
}
E:\課件\網(wǎng)絡(luò)安全
E:\課件\網(wǎng)絡(luò)安全\網(wǎng)絡(luò)安全
E:\課件\網(wǎng)絡(luò)安全.zip
-------------分隔符---------------
E:\課件
E:\課件\批判閱讀
E:\課件\批判閱讀\Unit One.doc
E:\課件\網(wǎng)絡(luò)安全
E:\課件\網(wǎng)絡(luò)安全\網(wǎng)絡(luò)安全
E:\課件\網(wǎng)絡(luò)安全\網(wǎng)絡(luò)安全\crypto-10.ppt
E:\課件\網(wǎng)絡(luò)安全\網(wǎng)絡(luò)安全\crypto-11.ppt
E:\課件\網(wǎng)絡(luò)安全\網(wǎng)絡(luò)安全\crypto-13.ppt
E:\課件\網(wǎng)絡(luò)安全\網(wǎng)絡(luò)安全\crypto-14.ppt
...
遞歸復(fù)制文件
fun main() {
val f = File("./") // 當前項目文件夾
val target = File("../tmep/") // 復(fù)制到上一級目錄
f.copyRecursively(target, true) // 遞歸復(fù)制
}
2 網(wǎng)絡(luò)IO
fun main() {
val html = URL("https://www.baidu.com").readText()
println(html)
}
3 執(zhí)行shell指令
只需要對String類進行擴展即可
fun String.execute(): Process {
return Runtime.getRuntime().exec(this)
}
fun Process.text(): String {
val isr = InputStreamReader(this.inputStream)
val reader = BufferedReader(isr)
var line: String? = "";
var out = ""
while (line != null) {
line = reader.readLine()
out += line + "\n"
}
return out
}
這樣就可以這樣調(diào)用指令了
val p = "ls -al".execute()
val text = p.text()
4 正則表達式
matches
-
全部匹配為true,否則為false
val b1 = Regex("[a-z]+").matches("abcABC") //false val b2 = Regex("[a-z]+", RegexOption.IGNORE_CASE).matches("abcABC") // true
containsMatchIn
-
字符中至少一處匹配返回true
val b3 = Regex("[0-9]+").containsMatchIn("012abc") // true
matchEntire
-
如果全部匹配則規(guī)則則返回對象
val s4 = Regex("[0-9]+").matchEntire("1234abc")?.value
replace
replaceAll
find
findAll
fun main() {
val r1 = Regex("[a-z]+") //創(chuàng)建一個Regex 對象钻弄,匹配的正則表達式是[a-z]+
val r2 = Regex("[a-z]+", RegexOption.IGNORE_CASE)
val b1 = Regex("[a-z]+").matches("abcABC") //false
val b2 = Regex("[a-z]+", RegexOption.IGNORE_CASE).matches("abcABC") // true
val b3 = Regex("[0-9]+").containsMatchIn("012abc") // true
val s4 = Regex("[0-9]+").matchEntire("1234abc")?.value
println(s4) // null
val s5 = Regex("[0-9]+").replace("12abc", "xxxx")
val s6 = Regex("[0-9]").replace("1ABC2Z") { (it.value.toInt() * it.value.toInt()).toString() }
val s7 = Regex("[0-9]+").find("12BAC3D")
Regex("[0-9]+").findAll("12BAC3D").forEach { println(it.value) } // 12 3
// 使用Java正則表達式API
val re = Regex("[0-9]+")
val p = re.toPattern()
val m = p.matcher("888ABC999")
while (m.find()) {
val d = m.group()
println(d)
}// 888 999
}
5 多線程編程
Kotlin中沒有synchronized佃却、volatile關(guān)鍵字。Kotlin的Any類似于Java的Object窘俺,但是沒有wait()饲帅、notify()和notifyAll()方法。
創(chuàng)建線程
擴展Thread類或者進行實例化并通過構(gòu)造函數(shù)傳遞一個Runnable瘤泪。因為我們可以很容易地在Kotlin中使用Java類灶泵,所以這兩個方式都可以使用。
fun main() {
//object 對象表達式,匿名類繼承
object : Thread() {
override fun run() {
Thread.sleep(3000)
println("A 使用Thread 對象表達式: ${Thread.currentThread()}")
}
}.start()
// Lambda 表達式对途,實際上 lambda 代替 runnable接口作為參數(shù)傳入
Thread {
Thread.sleep(2000)
println("B 使用Lambda 表達式: ${Thread.currentThread()}")
}.start()
// 使用kotlin封裝的thread函數(shù)
thread(start = true, isDaemon = false, name = "DThread", priority = 3) {
Thread.sleep(1000)
println("D 使用Kotlin 封裝的函數(shù)thread(): ${Thread.currentThread()}")
}
}
同步方法和塊
synchronized不是Kotlin中的關(guān)鍵字赦邻,它替換為@Synchronized注解。
fun main() {
@Synchronized fun f() {
}
// 同步代碼塊
fun f2(){
synchronized(Any()){
}
}
}
和Java的代碼基本上一樣
可變字段
Kotlin中沒有volatile關(guān)鍵字掀宋,取而代之的是@volatile注解深纲,效果和volatile一致