I would like to execute 2 or more commands sequentially through my Java Application using ProcessBuilder class. I Have tried multiple options as suggested in other responses/forums but no luck.
我希望通过使用ProcessBuilder类的Java应用程序顺序执行两个或多个命令。我尝试了多种选择,如在其他回复/论坛建议的,但没有运气。
Here are the things I have tried:
以下是我试过的:
ProcessBuilder processBuilder = new ProcessBuilder("ls", ";", "pwd");
Gives me following error :
给我以下错误:
Errors : ls: ;: No such file or directory Errors : ls: pwd: No such file or directory
错误:ls:;:没有此类文件或目录错误:ls: pwd:没有此类文件或目录
ProcessBuilder processBuilder = new ProcessBuilder("ls", "&&", "pwd");
Gives me similar error:
给我类似的错误:
Errors : ls: &&: No such file or directory Errors : ls: pwd: No such file or directory
错误:ls: && &没有这样的文件或目录错误:ls: pwd:没有这样的文件或目录。
List<String> command = new ArrayList<String>();
command.add("ls");
command.add(";");
command.add("pwd");
ProcessBuilder processBuilder = new ProcessBuilder(command);
Gives me following error:
给我以下错误:
Errors : ls: ;: No such file or directory Errors : ls: pwd: No such file or directory
错误:ls:;:没有此类文件或目录错误:ls: pwd:没有此类文件或目录
My OS is Linux/Mac-OSX.
我的操作系统是Linux / mac osx。
2 个解决方案
#1
20
Your approaches are equivalent to calling ls
with the specified arguments. In Bash notation, what you're running is:
您的方法等同于使用指定的参数调用ls。在Bash表示法中,您正在运行的是:
ls ';' pwd
ls '&&' pwd
If you want ls
and pwd
to be run as separate commands, you can use Bash (or another shell language) to wrap them into a single command:
如果您希望ls和pwd作为单独的命令运行,您可以使用Bash(或其他shell语言)将它们封装到一个命令中:
bash -c 'ls ; pwd'
which you can call this way:
你可以这样称呼它:
ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", "ls ; pwd");
#2
1
You could get the Process from ProcessBuilder.start() from the first command, wait using waitFor() and then launch the second one.
您可以从第一个命令processbuild .start()获取进程,使用waitFor()等待,然后启动第二个命令。
#1
20
Your approaches are equivalent to calling ls
with the specified arguments. In Bash notation, what you're running is:
您的方法等同于使用指定的参数调用ls。在Bash表示法中,您正在运行的是:
ls ';' pwd
ls '&&' pwd
If you want ls
and pwd
to be run as separate commands, you can use Bash (or another shell language) to wrap them into a single command:
如果您希望ls和pwd作为单独的命令运行,您可以使用Bash(或其他shell语言)将它们封装到一个命令中:
bash -c 'ls ; pwd'
which you can call this way:
你可以这样称呼它:
ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", "ls ; pwd");
#2
1
You could get the Process from ProcessBuilder.start() from the first command, wait using waitFor() and then launch the second one.
您可以从第一个命令processbuild .start()获取进程,使用waitFor()等待,然后启动第二个命令。