[英]How to execute and read 2 terminal commands in one process on MacOS in Java
我正在嘗試構建一個 Android Studio 插件,它允許我將更改的文件 (Git) 復制到剪貼板。 我能夠獲得 .git 文件所在的根路徑。 然后我想在這個路徑中執行命令git diff --name-only
。 因此我必須首先執行cd <path>
。 我可以一個接一個地執行,但不能與&&
運算符 fe 一起執行。 然后輸入流中什么都沒有。 是不是因為我目前正在使用需要其他命令的 Mac? 我搜索了幾個小時的解決方案,但似乎沒有任何效果。
這是我的方法:
class MyAction: AnAction() {
override fun actionPerformed(event: AnActionEvent) {
println("Action Performed")
val path = ModuleRootManager.getInstance(ModuleManager.getInstance(event.project!!).modules[0]).contentRoots[0].path
println("Path: $path")
try {
runCommand(path, "git diff --name-only")
} catch (e: Exception) {
e.printStackTrace()
println("Path is incorrect")
}
}
private fun runCommand(path: String, command: String) {
val rt = Runtime.getRuntime()
val pathCommand = "cd $path "
val proc = rt.exec(pathCommand + "&& " + command)
printInput(proc)
}
private fun printInput(proc: Process) {
printProcessInput(proc)
printProcessError(proc)
}
private fun printProcessInput(proc: Process) {
println("Here is the standard output of the command:\n")
printStream(proc.inputStream)
}
private fun printProcessError(proc: Process) {
println("Here is the standard error of the command (if any):\n")
printStream(proc.errorStream)
}
private fun printStream(stream: InputStream) {
val stdInput = BufferedReader(InputStreamReader(stream))
var s: String?
while (stdInput.readLine().also { s = it } != null) {
println(s)
}
}
}
我找到了解決方案。 如果你想導航到一個目錄並在那里執行命令,你可以使用 ProcessBuilder 並像這樣定義目錄:
private fun runProcess(path: String): Process {
val file = File(path)
val processBuilder = ProcessBuilder()
return processBuilder.command("git", "diff", "--name-only")
.directory(file)
.start()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.