如何从Java代码运行不同的命令? [英] How to run Different commands from Java Code?

查看:103
本文介绍了如何从Java代码运行不同的命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行不同的命令,这些命令可以在我的命令提示符或终端上通过Java执行。

I want to run different commands which can be executed on my command prompt or terminal through Java.

我搜索了几个地方,但没有得到适当的答复。

I did search few place but did not get appropriate reply.

我想运行一个在环境中设置为VISAGE_HOME的编译器,并运行GRADLE以完成所有构建任务。

I want to run a compiler which is set in the environment as VISAGE_HOME as well as run GRADLE so as to do all my build tasks.

我想从Java程序中调用所有这些命令。

I want to invoke all these commands from within Java Program.

因为它是一个swing应用程序我会喜欢在点击按钮或其他一些事件时调用这些命令。

Since it is a swing application I would like to invoke these commands on click of button or some other events.

我的问题是我无法编程:(。

My Problem is that I am not able to program this :( .

我也不知道会有这样做的API。我经历了一些示例代码,但大多数都有相同类型的执行shell命令或命令提示命令的示例代码。没有让我看到上面的东西。

Neither do I know an API which would do this. I went through some sample codes but most of them have same kind of example codes of executing the shell commands or command prompt commands. None showed me to do the above stuff.

推荐答案

看看 ProcessBuilder 。它返回的Process对象有一个 waitFor 方法,这样您就可以等待该过程完成。然后您就可以开始了你的下一个过程。

Have a look at ProcessBuilder. The Process object it returns has a waitFor method so you can wait for the process to finish. Then you can start your next process.

例如

Process p = new ProcessBuilder("runYourCommand").start();
InputStream in = process.getInputStream();
InputStreamReader inr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inr);
String inputLine;
while ((inputLine = br.readLine()) != null) {
  System.out.println(inputLine);
}
p.waitFor();

ProcessBuilder上另一个有趣的方法是环境()。这将返回您可以访问的环境变量。来自API文档

Another interesting method on ProcessBuilder is environment(). This will return the environment variables that you can access. From the API docs

Map<String, String> env = pb.environment();  
env.put("VAR1", "myValue");

这篇关于如何从Java代码运行不同的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆