在这种特殊情况下,您可以使用 AppleScript 打开终端来伪造它:
final ProcessBuilder processBuilder = new ProcessBuilder(
"/usr/bin/osascript", "-e");
final Map<String, String> environment = processBuilder.environment();
final String path = environment.get("PATH");
processBuilder.command().add("tell application \"Terminal\" to do script \"" +
"cd /Volumes ; export PATH=\\\"/mypath:" + path + "\\\\"\"");
final Process process = processBuilder.start();
process.waitFor();
如果您想从用户提供的参数中填充cd
目录和PATH
值,那么我会考虑使用on run
让脚本接受参数,并使用quoted form of
以避免任何潜在的引用问题:
final ProcessBuilder processBuilder = new ProcessBuilder("/usr/bin/osascript",
"-e", "on run argv",
"-e", " tell application \"Terminal\" to do script "
+ "\"cd \" & quoted form of item 1 of argv & \" ; "
+ "export PATH=\" & quoted form of item 2 of argv",
"-e", "end run");
// create a File and use getAbsolutePath to resolve any relative paths
// against this Java process's working directory.
File cdDir = new File(dirParam);
// this argument will be "item 1 of argv" to the AppleScript
processBuilder.command().add(cdDir.getAbsolutePath());
final Map<String, String> environment = processBuilder.environment();
final String path = environment.get("PATH");
File pathPrefix = new File(pathParam);
// and this will be "item 2 of argv"
processBuilder.command().add(
pathPrefix.getAbsolutePath() + File.pathSeparator + path);
final Process process = processBuilder.start();
process.waitFor();
如果你不能getAbsolutePath
在 Java 端做到这一点,但仍然希望相对路径(相对于 的当前目录osascript
)起作用,那么你需要这样的技巧:
final ProcessBuilder processBuilder = new ProcessBuilder("/usr/bin/osascript",
"-e", "on run argv",
"-e", " set currentdir to (do shell script \"pwd\")",
"-e", " set currentpath to (do shell script \"echo $PATH\")",
"-e", " tell application \"Terminal\" to do script \""
+ "cd \" & quoted form of currentdir & \" ; ""
+ "cd \" & quoted form of item 1 of argv & \" ; "
+ "export PATH=\" & quoted form of currentpath",
"-e", "end run",
dirParam);
final Map<String, String> environment = processBuilder.environment();
final String path = environment.get("PATH");
environment.put("PATH", pathParam + File.pathSeparator + path);
final Process process = processBuilder.start();
process.waitFor();
这有点像俄罗斯玩偶——我们osascript
从 Java 执行,它又运行自己的子 shell 来执行pwd
并将echo $PATH
当前工作目录的值和osascript 进程PATH
的变量放入 AppleScript 变量中,然后我们将其注入进入新航站楼。通过首先对“当前”目录执行一个操作,然后对指定的另一个执行操作,这将处理相对路径和绝对路径。cd
cd
dirParam
最后请注意osascript
打印脚本的返回值,因此您应该确保在执行之前使用所有进程输出waitFor
(或者如果您使用的是 Java 7,您可以使用processBuilder.redirectOutput(new File("/dev/null"))
和相同的 for redirectError
)。