2

Main intention is to set the environment variables through java code.

Process process = Runtime.getRuntime().exec("export MY_ENV=123");

Always returns a new process. But I want it to be executed for the current process .. Is there a way to append output to the current process?

Cœur
  • 37,241
  • 25
  • 195
  • 267
shashantrika
  • 1,039
  • 1
  • 9
  • 29
  • 1
    See also [When Runtime.exec() won't](http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html) for many good tips on creating and handling a process correctly. Then ignore it refers to `exec` and use a `ProcessBuilder` to create the process. – Andrew Thompson Oct 07 '14 at 19:13
  • 2
    This has been answered [over here](http://stackoverflow.com/questions/318239/how-do-i-set-environment-variables-from-java). It's not a good idea to change the whole question like that. I suggest you revert your edit. – aioobe Oct 08 '14 at 17:48

2 Answers2

3

Use ProcessBuilder

  • inheritIO lets you hook up the streams of the started process with the current process
  • waitFor allows you to wait for the external process to finish

Example:

new ProcessBuilder("/bin/ls").inheritIO()
                             .start()
                             .waitFor();
aioobe
  • 413,195
  • 112
  • 811
  • 826
0

The Process returned from the exec call contains three streams:

  1. process.getOutputStream() which, if you write to, will be 'piped' in to the running process
  2. process.getInputStream() which, if read from, will contain the standard output (the ls output)
  3. process.getErrorStream() whihc, if read from, will contain the standard error output (error messages from running ls, if any).

It is your responsibility as the programmer, to read from these streams, and to output them to your program's output, if that's what you want.

Also, you should check the process.exitValue() if you want to get that too.

it is somewhat common to set up separate threads to monitor the Stdout and Stderr streams

rolfl
  • 17,539
  • 7
  • 42
  • 76