如何在Java中执行本机命令?
我非常清楚如何通过 Runtime.getRuntime().exec(command) 执行命令并处理输出,但这非常有限。
以 Windows 为例(特别是 Vista,但这并不重要)。
如何通过 Java 中的 ProcessBuilder(或任何类)执行“echo”、“cd”、“md”、“rd”等命令以及任何其他植根于 cmd.exe 内部的命令?
I know very well how to execute commands via Runtime.getRuntime().exec(command) and handle the output, but this is VERY limited.
Take Windows for example (Vista specifically but that shouldn't matter).
How can I execute commands like 'echo', 'cd', 'md', 'rd', and any other command rooted inside of the cmd.exe through ProcessBuilder (or whatever class) in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需在 Runtime.exec 或 ProcessBuilder 或其他方式中调用
cmd /c dir
而不仅仅是dir
即可在 JAVA 中运行外部应用程序。You just call
cmd /c dir
rather than justdir
in Runtime.exec or ProcessBuilder or some other way to run external applications in JAVA.另一个技巧是利用 Ant 库并将
的编程版本放在一起(Ant Exec 任务)。这还使您可以访问 Ant 支持的各种输入/输出处理和过滤。这里不是编写 Ant XML 脚本,而是从代码中调用 Ant。
Another trick is to leverage the Ant libraries and put together a programmed version of
<exec ...>
(Ant Exec Task). This also gives you access to all kinds of Ant-supported input/output processing and filtering.This is not writing an Ant XML script here, but calling Ant from your code.