I am trying to execute windows commands from Java using the following code,
Process p=Runtime.getRuntime().exec("wget www.anyurl.com/index.html);
and it works but when I try to execute another command which is as follows,
Process p1=Runtime.getRuntime().exec("pscp -pw sysadmin c:/mydirectory/mypage.html mahesh@vmstni01:/home/usr");
it does not seem to work. If I comment out the first process line (ie Process p) then the process p1 is working fine, it executes and shows that file has been copied successfully. Please can anyone tell me why this is happening?
You need to clean up the streams of the first process, otherwise the program will block because the "wget" process produces output that is never read in your current implementation. You need to sort out the output and error streams of the first process. Look at answers to e.g. another question about java-runtime-exec on SO.
The code below works for reference, but relies on the fact that wget generates output to stderr and pscp to stdout. If anything gets output to the other corresponding stream, the code works as long as the output fits into the buffer of the Java program (please note that these buffer sizes tend to be different from platform to platform) while it empties the first stream. If the buffer gets full, the execution of the command simply blocks. You should create a separate thread for both, stout and stderr that reads the appropriate stream of the process.
import java.io.BufferedReader;
import java.io.InputStreamReader;
...
Process p=Runtime.getRuntime().exec("wget http://www.duckduckgo.com/");
BufferedReader perr=new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader pout=new BufferedReader(new InputStreamReader(p.getInputStream()));
// We read stderror first from wget, because it spits the progress information into stderr
for (String s=perr.readLine(); s!=null; s=perr.readLine())
{
System.out.println("Stderr from p: "+s);
}
for (String s=pout.readLine(); s!=null; s=pout.readLine())
{
System.out.println("Stdout from p: "+s);
}
// if you need to check whether the command actually returned normally
int returnCode = p.waitFor();
perr.close();
pout.close();
System.out.println("Returned from p with exit code "+returnCode);
p=Runtime.getRuntime().exec("pscp -pw dontuseplainpwusesshkeys index.html user@10.0.0.11:");
perr=new BufferedReader(new InputStreamReader(p.getErrorStream()));
pout=new BufferedReader(new InputStreamReader(p.getInputStream()));
// We read stdout of pscp first because pscp spits stuff into stdout.
// The process will block if the buffer gets full and does not get emptied.
for (String s=pout.readLine(); s!=null; s=pout.readLine())
{
System.out.println("Stdout from p: "+s);
}
for (String s=perr.readLine(); s!=null; s=perr.readLine())
{
System.out.println("Stderr from p: "+s);
}
int returnCode1 = p.waitFor();
perr.close();
pout.close();
System.out.println("Process exited with return code "+returnCode1);