从 Java 启动外部控制台应用程序
在 Java 应用程序中,我需要运行外部控制台应用程序。对于窗口的一切都很好:
try {
System.out.println("Running...");
Runtime.getRuntime().exec("notepad.exe");
System.out.println("End.");
}
catch(Exception e) {
System.out.println(e.getMessage());
}
成功启动记事本。
但是如果我输入 D:\\MyProg.exe
或 .bat
甚至 cmd.exe
(它是记事本的 PATH )不起作用。无一例外。只是:
Running...
End.
in a Java application I need to run an external console application. With the window's ones everything is OK:
try {
System.out.println("Running...");
Runtime.getRuntime().exec("notepad.exe");
System.out.println("End.");
}
catch(Exception e) {
System.out.println(e.getMessage());
}
launches notepad successfully.
But if I put D:\\MyProg.exe
or .bat
or even cmd.exe
(which is it PATH as notepad is) it does not work. Without any exeptions. Just:
Running...
End.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,
Runtime.exec()
很可能会异步返回,因此只需打印“end”就始终有效,因为 exec 调用会立即返回,这就是您所看到的。这里可能会出现很多其他问题。我认为正在发生的情况是,您正在调用的程序可能会在您无法读取的标准输出上输出 I/O,或者您可能需要 等待其完成,然后退出 java 进程。有一篇关于各种问题的很棒的文章对于
Runtime.exec()
您可能应该阅读,它涵盖了这个问题和其他问题。First off, most likely
Runtime.exec()
is returning asynchronously, so just printing "end" will always work, since the exec call returns immediately, which is what you're seeing.There's a bunch of other problems that could be showing up here. I think what is happening is that the programs you are calling might be outputting I/O on stdout that you are failing to read, or perhaps you need to wait for it to finish before exiting the java process. There's a great article on the various problems with
Runtime.exec()
you should probably read, it covers this and other problems.这是因为记事本放置在特殊文件夹中,并且该文件夹存在于
Path
变量中。使用以下行运行
cmd
:运行其他应用程序:
It is because notepad placed in special folder and this folder exists in
Path
variable.Run
cmd
using following line:Run other application: