Reputation: 43
I'm running following code :
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "echo hello");
Process p = pb.start();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line, l = "";
while ((line = bufferedReader.readLine()) != null) {
System.out.println(l);
l = l + line;
}
p.destroy();
bufferedReader.close();
System.out.println("completed");
ProcessBuilder pb1 = new ProcessBuilder("cmd.exe", "/C", "echo hi");
Process p1 = pb1.start();
line = "";
BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
while ((line = bufferedReader1.readLine()) != null) {
l = l + line;
System.out.println(l);
}
p1.destroy();
bufferedReader1.close();
System.out.println("completed");
}
But while running my code the result has been extracted correctly by the two buffer-reader
.
The problem is that the execution of the program is not terminated and it gets hanged.
Upvotes: 1
Views: 4261
Reputation: 59950
Why you don't create a method that take your command
and return your result
, like this you can execute many commands, and you can use it every where in your program, and if you need some changes you just change in this method and not in all your program:
Your code should be like so:
public static void main(String[] args) {
String command1 = "echo hello";
String command2 = "echo hi";
System.out.println(executerCommand(command1));
System.out.println(executerCommand(command2));
}
public static String executCommand(String command) {
String line;
String resultat = "";
try {
ProcessBuilder builder;
builder = new ProcessBuilder("cmd.exe", "/c", command);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
while (true) {
line = r.readLine();
if (line == null) {
break;
}
resultat += line + "\n";
}
} catch (IOException e) {
System.out.println("Exception = " + e.getMessage());
}
return resultat;
}
This return a result like this :
run: hello hi BUILD SUCCESSFUL (total time: 0 seconds)
Hope this can help you
Upvotes: 2