简体   繁体   中英

Starting an external program in Java and piping it's output

This might seem a bit awkward but I want to start a console program in Java but in it's own window, while at the same time using tee to save the output in a log file. I am porting the program that does this from Perl to Java and am having problems starting the program with lots of command argumments. In Perl it uses

system("dtterm -title $title -e /usr/bin/ksh -c \"".
"cd $dir; ./$exec $arg | tee $exec.log \" &");

I am trying to use the ProcessBuilder class to do the same.

ProcessBuilder builder = new ProcessBuilder("dtterm", "-title", title, "-e",
"/usr/bin/ksh", "-c" "./" + exec, arg, "|", "tee", exec + ".log");
builder.directory(dir);
Process process = builder.start();

While doing this, the process starts, it doesn't pipe into the log file as well, yet it does from the Perl. I have tried using the builder.getInputStream() method but since it is shown in the dtterm window there is no output from the out process.

I need to have separate windows because the program launches several different programs at the same time, each with its own windows. I did try launching it directly and send the output from all the processes to my program stdout but there was too much, it needs to be kept separate. If there is no way of doing this then I will have to make a JFrame that shows the output of the program but I would like to avoid that if possible.

You need to build up your command a bit differently. What you want is:

dtterm -title <title> -e /usr/bin/ksh -c "./<exec> arg | tee <exec>.log"

(Note the quotes around the parameter to ksh .) You need to replicate this in your code:

ProcessBuilder builder = new ProcessBuilder("dtterm", "-title", title, "-e", "/usr/bin/ksh", "-c", "./" + exec + " arg + " | tee " + exec + ".log");

Yes, this looks very ugly, and you have to watch out to escape exec properly in case it contains special characters like space, or quotes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM