Kotlin 执行Shell命令

Kotlin 执行Shell命令,第1张

Kotlin 执行Shell命令
  1. 扩展String类
  2. 扩展Process类
  3. 测试
fun String.execute(): Process {
    val runtime = Runtime.getRuntime()
    return runtime.exec(this)
}
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)
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5687172.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存