在 Java 中运行命令行
有没有办法在 Java 应用程序中运行此命令行?
java -jar map.jar time.rel test.txt debug
我可以用命令运行它,但我无法在 Java 中运行它。
Is there a way to run this command line within a Java application?
java -jar map.jar time.rel test.txt debug
I can run it with command but I couldn't do it within Java.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
http://docs.oracle.com/javase/7 /docs/api/java/lang/Runtime.html
http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
您还可以像这样观察输出:
并且不要忘记,如果您正在运行 Windows 命令,则需要将
cmd /c
放在命令前面。编辑:为了获得奖励积分,您还可以使用 ProcessBuilder 将输入传递给程序:
这将运行 Windows 命令choice /C YN /M“Press Y if you're Cool” 并用
Y
响应。所以,输出将是:You can also watch the output like this:
And don't forget, if you are running a windows command, you need to put
cmd /c
in front of your command.EDIT: And for bonus points, you can also use
ProcessBuilder
to pass input to a program:This will run the windows command
choice /C YN /M "Press Y if you're cool"
and respond with aY
. So, the output will be:为了避免被调用的进程在标准输出上输出大量数据和/或错误时被阻止,您必须使用 Craigo 提供的解决方案。另请注意,ProcessBuilder 优于 Runtime.getRuntime().exec()。这有几个原因:它更好地标记参数,并且还处理错误标准输出(另请检查 此处)。
我使用新函数“watch”在新线程中收集这些数据。当被调用进程结束时,该线程将在调用进程中完成。
To avoid the called process to be blocked if it outputs a lot of data on the standard output and/or error, you have to use the solution provided by Craigo. Note also that ProcessBuilder is better than Runtime.getRuntime().exec(). This is for a couple of reasons: it tokenizes better the arguments, and it also takes care of the error standard output (check also here).
I use a new function "watch" to gather this data in a new thread. This thread will finish in the calling process when the called process ends.
如果您遇到任何其他问题,请考虑以下内容,但我猜上述内容对您有用:
Runtime.exec() 的问题
Consider the following if you run into any further problems, but I'm guessing that the above will work for you:
Problems with Runtime.exec()
怎么样
what about
您是否尝试过 Runtime 类中的 exec 命令?
运行时- Java文档
Have you tried the exec command within the Runtime class?
Runtime - Java Documentation