Java – Porting a Bash Script to Java

bashjava

I'm attempting to emulate the functionality of the bash shell script below using a Process or ProcessBuilder object in Java. It's not 100% clear to me how I do the redirection for standard-in. How can I accomplish this?

#
#  Redirect shell echo command from standard output to file
#  This will construct the input file
# 
exec 1> $STDIN
echo -e "$NFILE\n$GFILE\n$INPUT\n$OUTPUT\n$CAX"
exec 1>&-

#
#  Run executable redirecting standard in as the input file and output to a log file
#
"$EXE" < $STDIN >& $LOG

Best Answer

The Process object streams are misleadingly named. You need to write to the OutputStream of the Process object.

From the doc:

All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()).

You also have to consume the process output and standard error concurrently, otherwise buffers will fill up and the process will block. See here for more information.