try { String str; Process process = Runtime.getRuntime().exec("bash /home/abhishek/workspace/Pro/run"); InputStream isout = process.getInputStream(); InputStreamReader isoutr = new InputStreamReader(isout); BufferedReader brout = new BufferedReader(isoutr); while ((str = brout.readLine()) != null) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); }
The Code has issues with getting the InputStream from the Process, because if I run the Shell script from my Terminal it runs completely fine, but if I Run the Script like this,the str is always null,
I am using this code to get the output of the Shell Script directly into Java instead writing the Script Output in the File
Is there any other way to achieve this,or how can I get the issue solved using the current approach
Advertisement
Answer
I think something returned through the error stream, so you can try to check something from the Process.getErrorStream().
You should also wait for the created process to prevent your main program completes before it. Use Process.waitFor();
public class TestMain { private static final String BASH_CMD = "bash"; private static final String PROG = "/home/abhishek/workspace/Pro/run"; private static final String[] CMD_ARRAY = { BASH_CMD , PROG }; public static void main(String[] args) { new Thread(new Runnable() { public void run() { BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); String command = null; try { while ((command = reader.readLine()) != null) { System.out.println("Command Received:" + command); } } catch (Exception ex) { ex.printStackTrace(); // failed to listening command } } }).start(); Process process = null; try { ProcessBuilder processBuilder = new ProcessBuilder(CMD_ARRAY); process = processBuilder.start(); InputStream inputStream = process.getInputStream(); setUpStreamGobbler(inputStream, System.out); InputStream errorStream = process.getErrorStream(); setUpStreamGobbler(errorStream, System.err); System.out.println("never returns"); process.waitFor(); } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } } public static void setUpStreamGobbler(final InputStream is, final PrintStream ps) { final InputStreamReader streamReader = new InputStreamReader(is); new Thread(new Runnable() { public void run() { BufferedReader br = new BufferedReader(streamReader); String line = null; try { while ((line = br.readLine()) != null) { ps.println("process stream: " + line); } } catch (IOException e) { e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }).start(); } }