作者:许更剑_725 | 来源:互联网 | 2023-06-05 11:13
***调用系统命令行中的命令.以List的方式输入命令的各个参数.*命令执行完毕后会以String?传回结果,不会在终端显示*默认在当前目录中执行,超时时间为60秒
/**
* 调用系统命令行中的命令.以List的方式输入命令的各个参数.
* 命令执行完毕后会以String?传回结果,不会在终端显示
* 默认在当前目录中执行,超时时间为60秒
*/
fun runCommand(
cmd: List,
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?传回结果,不会在终端显示
* 在当前目录中执行,超时时间为60秒.
* 若要更改目录和时间,请使用List的方式传入
*/
fun runCommand(vararg cmd: String): String? = runCommand(listOf(*cmd))
//不推荐这样使用,程序遇到错误会直接退出.
fun String.runCommand(): String = Runtime.getRuntime().exec(this).inputStream.bufferedReader().readText()