2

My Shell script named "hello"

#This is a shell script
echo "Hello Shell World!"

My Java Code,

Runtime.getRuntime().exec(new String[]{"./hello"});

My Java code is executed with no errors, but I do not see "Hello Shell World!" being printed on the terminal.

I believe my script is being executed since I do not get errors like, "hello cannot be executed, there is no such file or directory".

I am executing this on a Linux machine, Ubuntu. Thanks!

1

2 Answers 2

2

When running an external program from Java the output does not go to (and the input does not come from) the Java application's terminal.

The input and output streams (STDIN, STDOUT, STDERR) to the external program (your script) are directed to (from) InputStreams and OutputStreams that are accessible from the Java Process that is created when you do the exec(...)

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

1 Comment

Thank you so much! Your first line of the answer explained it all.
1

You should use a reader to capture the output of the command:

Process p=Runtime.getRuntime().exec(new String[]{"./hello"});
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null) {
    System.out.println(line);
    line=reader.readLine();
}

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.