Kotlin 执行Shell命令

时间:2025-02-08 09:16:00
  1. 扩展String
  2. 扩展Process
  3. 测试
/**
 * 给String扩展 execute() 函数
 */
fun String.execute(): Process {
    val runtime = Runtime.getRuntime()
    return runtime.exec(this)
}
/**
 * 扩展Process扩展 text() 函数
 */
fun Process.text(): String {
    // 输出 Shell 执行结果
    val inputStream = this.inputStream
    val insReader = InputStreamReader(inputStream)
    val bufReader = BufferedReader(insReader)

    var output = ""
    var line: String? =""
    while (null!=line) {
        // 逐行读取shell输出,并保存到变量output
        line = bufReader.readLine()
        output += line +"\n"
    }
    return output
}
// 测试
fun testShell(): Unit {
    val process = "ls -al".execute()
    val exitCode = process.waitFor()
    val text = process.text()
    println(exitCode)
    println(text)
}