Java external program
I'd like to start external third party application from my Java application. This external application should run all the time whilst my java application runs.
From time to time (it depends on user interaction) my java app should be able to read and write to this external application 开发者_运维技巧via stdin
and stdout
.
How can I do that?
Essentially, you will need multiple threads in Java that watch for the outside process to end and which shuffle around its input/output/error streams so that your main Java app has access to it.
There are more "basic" ways to do it with classes like Process
, but I would suggest Apache Commons-exec, which provides some useful tools for handling return values and I/O.
As you are implementing the suggestion of starting a Process
, read and implement all the recommendations of When Runtime.exec() won't.
Also consider using a ProcessBuilder
in place of Runtime.exec()
(if coding for 1.5+).
Is ex-app native code, or another Java program? If it's native code, look at http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Process.html and http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html
Those will allow you to execute a native program, keep track of its status, and get its output and send it input.
It depends on the specifics of the external application, mainly: 3rd party or is it something you have control over?... what it's built with, what it's capabilities are, etc.
A 'kludgy' method would be to simply use the file system and have Java watch for files dropped in a specific location (taking care to handle locked files appropriately). A more sophisticated method would be to communicate via sockets, or writing to a database table within a local/internally hosted db such as hsqldb. Using in/out streams via java.lang.Process might also do the trick, depending on the 3rd party app of course.
But again all of this depends on the specifics of the application you're communicating with. Java's Process class isn't going to help if the 3rd party app is Excel (in which case you'd probably have to watch a save directory for xls files per the first method I mentioned).
精彩评论