问题
I just conducted simple test code for Java Process Builder. There are 4 examples and everything is working smoothly excluding last one. Here is my codes
public class bashProcessor {
public static void main(String args[]) {
try {
ProcessBuilder pb;
pb = new ProcessBuilder("/bin/bash", "-c", "touch Jin_1.sh");
pb.start();
pb = new ProcessBuilder("/bin/bash", "-c", "mkdir Jin_2");
pb.start();
pb = new ProcessBuilder("/bin/bash", "-c", "bash /home/Jin/test.sh");
pb.start();
//below is not working
pb = new ProcessBuilder("/bin/bash", "-c",
"bash /home/solr-tomcat/bin/shutdown.sh warm4 solr-instances");
pb.start();
System.out.println("pb job is done now");
Thread.sleep(3000);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
When I type last example(bash /home/solr...) by hand-typing. It works without any error. I need your kind help. if you have any idea please let me know it would be great help.
回答1:
As pointed out by @ug_ try to remove bash
from command and then execute your code. Following code works fine with multiple command.
cmd.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class cmd {
public static void main(String[] args) {
try {
String[] command = new String[3];
command[0] = "/bin/bash";
command[1] = "-c";
command[2] = "javac -verbose HelloWorld.java";
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String Error;
while ((Error = stdError.readLine()) != null) {
System.out.println(Error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
来源:https://stackoverflow.com/questions/35837355/java-simple-process-builder-issue