Reputation: 6472
I am on OSX 10.8.5 and trying to run terminal commands from Java.
So with the code below, I can read the output of Runtime.getRuntime().exec for some commands but not others.
You will see that some commands return their output just fine like ls and ifconfig, but then trying to get openssl to return its output either returns nothing or hangs depending on the implementation.
I have also used two different methods of reading the output but same results with both.
What is preventing certain commands from returning any output?
theCommand = "ls"; //this command works OK and returns its output
//theCommand = "ifconfig"; //this command works OK and returns its output
//theCommand = "openssl rand"; //this command does not return any output
//theCommand = "/bin/sh openssl rand"; //this command does not return any output
//theCommand = "/bin/sh -c openssl rand"; //this command hangs
try {
System.out.println("trying...");
Process extProc=Runtime.getRuntime().exec(theCommand);
extProc.waitFor();
//READ ouput attempt #1 - this works okay for ls and ifconfig command
//BufferedReader readProc=new BufferedReader(new InputStreamReader(extProc.getInputStream()));
//while(readProc.ready()) {
// theReadBuffer = readProc.readLine();
// System.out.println(theReadBuffer);
//}
//READ output attempt #2 - this works okay for ls and ifconfig command
InputStream theInputStream = extProc.getInputStream();
java.util.Scanner theScanner = new java.util.Scanner(theInputStream).useDelimiter("\\A");
if (theScanner.hasNext()) {
theReadBuffer = theScanner.next();
System.out.println(theReadBuffer);
}
} catch( IOException e) {
System.out.println(e.getMessage());
} catch(InterruptedException e) {
System.out.println(e.getMessage());
}
I am ultimately trying to generate random characters from this command (which works in terminal):
openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//'
Thanks
Upvotes: 1
Views: 1542
Reputation: 6472
Okay so thanks to Mark W comment to original question I realized that some commands output to stderr (use getErrorStream) and some to stdout (use getInputStream).
So doing something like this allows you to read from either:
BufferedReader readInputProc=new BufferedReader(new InputStreamReader(extProc.getInputStream()));
while(readInputProc.ready()) {
theReadBuffer = readInputProc.readLine();
System.out.println(theReadBuffer);
}
BufferedReader readErrorProc=new BufferedReader(new InputStreamReader(extProc.getErrorStream()));
while(readErrorProc.ready()) {
theReadBuffer = readErrorProc.readLine();
System.out.println(theReadBuffer);
}
Upvotes: 1