I am writing few programs to invoke cmd.exe with additional commands and collect the output generated from the same using java. Below is a sample program–
public class LoadShell {
public static void main(String[] args) throws Exception {
//Line1
String [] command ={"cmd.exe","/c","dir"};
ProcessBuilder probuilder = new ProcessBuilder( command );
Process process = probuilder.start();
InputStream inputstream1 = process.getInputStream();
InputStreamReader inputstreamreader1 = new InputStreamReader(inputstream1);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader1);
String line="";
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
}
}
}
These programs are working fine as expected. Now I have a simpler requirement. I want to invoke cmd.exe without any arguments and collect the output as String. This is because I want to send the process object reference and string to another method for some project specific purpose. So I have modified my code in Line1 as below–
public class LoadShell {
public static void main(String[] args) throws Exception {
//Line1
String [] command ={"cmd.exe"};
ProcessBuilder probuilder = new ProcessBuilder( command );
Process process = probuilder.start();
InputStream inputstream1 = process.getInputStream();
InputStreamReader inputstreamreader1 = new InputStreamReader(inputstream1);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader1);
int intch;
String line="";
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
}
}
}
But in this case, the readLine method hangs indefinitely after printing–
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
So I have also tried using read of BufferedReader instead of readline as follows —
while ((intch = bufferedreader.read()) != -1) {
int ch = (char) intch;
System.out.println(ch);
}
But even read is hanging after reading the bytes corresponding to —
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
Is there any way I can get the complete output that is below without causing my program to hang —
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\devshankhasharm>
Any ideas would be appreciated.
Probably because without the
/cflag you’re simply opening a shell window, and that external process is now sitting at theC:\>prompt waiting for a command to be issued. Since you never send anything, it’ll sit there until you kill it.