I have a java jar file which inturn calls a java program (command).
Command generated works fine when i run it in command promt.
Process proc = Runtime.getRuntime().exec("cmd.exe /C "+ Command);
BufferedReader stdIn = new BufferedReader(new
InputStreamReader(process.getInputStream()));
BufferedReader stdErr = new BufferedReader(new
InputStreamReader(process.getErrorStream()));
String output=null;
while((output=stdIn.readLine())!=null)
{
System.out.println("output is:"+output);
out.write(output);
out.newLine();
}
while((output=stdErr.readLine())!=null)
{
System.out.println("error output is:"+output);
out.write(output);
out.newLine();
}
try {
process.waitFor();
....
....
....
I tried ProcessBuilder:
ProcessBuilder proc = new ProcessBuilder("cmd.exe", "/C", Command); proc.redirectErrorStream(true);
proc.start();
But this throws error as:
java.io.IOException: Cannot run program "java -Xmx1024M ......"
CreateProcess error=2, The system cannot find the file specified
I can run the same command in promt which works absolutely fine.
With
new ProcessBuilder("cmd.exe", "/C", Command);
you have used the varargs overload of the constructor. This means that the command is assumed to be already parsed into the arguments. However, you are passing the complete Command
as a single argument, which means that cmd
will interpret the whole command line java -Xmx...
as just the command (file name) to run.
Either stick to the single string, relying on the ProcessBuilder
class to parse it, or pre-parse everything.
As for the hanging issue you have, there may be several causes:
out
stream is blocking; stderr
, which you don't read at all until it is already too late (the program has ended). Your second approach would fix this by merging stdout
and stderr
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.