• kotlin调用终端命令


    /**
     * 调用系统命令行中的命令.以List<String>的方式输入命令的各个参数.
     * 命令执行完毕后会以String?传回结果,不会在终端显示
     * 默认在当前目录中执行,超时时间为60秒
     */
    fun runCommand(
        cmd: List<String>,
        workingDir: File = File("."),
        timeoutAmount: Long = 60L,
        timeUnit: TimeUnit = TimeUnit.SECONDS
    ): String? = runCatching {
        ProcessBuilder(cmd)
            .directory(workingDir)
            .redirectErrorStream(true)
            .start().also { it.waitFor(timeoutAmount, timeUnit) }
    // jdk17之后这样写
            .inputReader().readText()
    // jdk17之前这样写
    //        .inputStream.bufferedReader().readText()
    }.onFailure { it.printStackTrace() }.getOrNull()
    
    
    /**
     * 调用系统命令行中的命令.以List<String>的方式输入命令的各个参数.
     * 命令执行完毕后会以String?传回结果,不会在终端显示
     * 在当前目录中执行,超时时间为60秒.
     * 若要更改目录和时间,请使用List<String>的方式传入
     */
    fun runCommand(vararg cmd: String): String? = runCommand(listOf(*cmd))
    
    //不推荐这样使用,程序遇到错误会直接退出.
    fun String.runCommand(): String = Runtime.getRuntime().exec(this).inputStream.bufferedReader().readText()
    
  • 相关阅读:
    快速排序
    常见的正则表达式验证(更新中)
    中介者模式
    RadioButtonList控件如何取得选中的值
    职责链模式
    设计模式之GOF23建造者模式
    设计模式之GOF23工厂模式02
    设计模式GOF23之工厂模式01
    多线程测试时的辅助类--CountDownLatch
    设计模式GOF23之单例模式
  • 原文地址:https://www.cnblogs.com/soclear/p/15690833.html
Copyright © 2020-2023  润新知