1

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Specify full path for the tools is useful and working. Thank you.
you should anyway get at least error stream output - if there are any other errors except wrong path, without the error stream you wouldn't have the information what it is about...
I did it ;) better late then never :)
0

Redirect the command's output to a tempfile like "ls > tempt.txt". That might fix the problem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.