I try to execute a basic command,which is “java -version”, in java code. My code works for the shell commands, in example “ls”, “echo $PATH” etc.
My code :
import java.io.*;
public class cmd {
public static void main(String[] args) {
String command = "java -version";
Process proc = null;
try {
proc = Runtime.getRuntime().exec(command);
} catch (IOException e1) {
System.out.println( "IOException 1" );
}
BufferedInputStream buffer = new BufferedInputStream( proc.getInputStream() );
BufferedReader commandOutput= new BufferedReader( new InputStreamReader( buffer ) );
String line = null;
try {
while ( ( line = commandOutput.readLine() ) != null ) {
System.out.println( line );
}
commandOutput.close();
} catch ( IOException e) {
System.out.println( "IOException 2" );
}
}
}
The code works without exception or error, but there is not an output.
If String command = “ls”, the code could be worked and the output could be seen in the console.
Check .getErrorStream() and .getOutputStream() of Process object that you have. You’ll likely see an error message there telling you that you need to specify full path to java executable for this to work. However, if the reason is something different, you should see that also when outputting the contents of mentioned streams.