Java外部程序
我想从我的 Java 应用程序启动外部第三方应用程序。当我的 java 应用程序运行时,这个外部应用程序应该一直运行。
有时(这取决于用户交互)我的 Java 应用程序应该能够通过 stdin
和 stdout
读取和写入此外部应用程序。
我怎样才能做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
本质上,您需要 Java 中的多个线程来监视外部进程的结束,并围绕其输入/输出/错误流进行洗牌,以便您的主 Java 应用程序可以访问它。
还有更多“基本”方法可以使用
Process
等类来完成此操作,但我建议 Apache Commons-exec,它提供了一些有用的工具来处理返回值和 I/O。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.当您实施启动
进程
的建议时,请阅读并实施所有建议-12-2000/jw-1229-traps.html" rel="nofollow">当 Runtime.exec() 不会时。还可以考虑使用
ProcessBuilder
< /a> 代替Runtime.exec()
(如果编码为 1.5+)。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 ofRuntime.exec()
(if coding for 1.5+).ex-app 是本机代码,还是另一个 Java 程序?如果是本机代码,请查看 http:// download.oracle.com/javase/1.5.0/docs/api/java/lang/Process.html 和 http://download.oracle.com/javase/1.5 .0/docs/api/java/lang/Runtime.html
这些将允许您执行本机程序、跟踪其状态、获取其输出并向其发送输入。
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.
这取决于外部应用程序的具体情况,主要是:第 3 方还是您可以控制的东西?...它是用什么构建的,它的功能是什么,等等。
一种“笨拙”的方法就是简单地使用文件系统并让 Java 监视放置在特定位置的文件(注意适当地处理锁定的文件)。更复杂的方法是通过套接字进行通信,或者写入本地/内部托管数据库(例如 hsqldb)中的数据库表。通过 java.lang.Process 使用输入/输出流也可能达到目的,当然具体取决于第 3 方应用程序。
但同样,所有这些都取决于您正在通信的应用程序的具体情况。如果第 3 方应用程序是 Excel,Java 的 Process 类将无济于事(在这种情况下,您可能必须按照我提到的第一种方法查看 xls 文件的保存目录)。
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).