如何在 Java 中的 MacOS 上在一个进程中执行和读取 2 个终端命令



我正在尝试构建一个Android Studio插件,它允许我将更改的文件(Git(复制到剪贴板。我能够获取 .git 文件所在的根路径。然后我想在此路径中执行命令git diff --name-only。因此,我必须首先执行cd <path>。我能够一个接一个地执行,但不能与&&操作员 f.e.然后输入流中没有任何内容。是因为我目前正在使用需要其他命令的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()
}

最新更新