kotlin函数
fun executeCMD(cmd: String, status: (String) -> Unit, result: (String) -> Unit) {
val runtime = Runtime.getRuntime()
val process = runtime.exec(cmd)
val code = process.waitFor()
val result1 = process.waitFor(3, TimeUnit.MINUTES)
status.invoke(code.toString())
if (code == 0) {
val message = getInReaderMessage(process.inputStream)
result.invoke(if (TextUtils.isEmpty(message)) "执行成功" else message.toString())
} else {
val message = getInReaderMessage(process.errorStream)
result.invoke(if (TextUtils.isEmpty(message)) "执行失败" else message.toString())
}
}
fun getInReaderMessage(stream: InputStream): String? {
val result = StringBuilder()
val lines = stream.bufferedReader().readLines()
for (line in lines) {
result.append(line).append("\r\n")
}
try {
stream.close()
} catch (e: Exception) {
e.printStackTrace()
}
return result.toString()
}
网友评论