当我们需要在java程序中调用外部程序,我们可用通过Runtime.exec()调用来完成。
The class java.lang.Runtime features a static method called getRuntime(), which retrieves the current Java Runtime Environment. That is the only way to obtain a reference to the Runtime object. With that reference, you can run external programs by invoking the Runtime class's exec() method. Developers often call this method to launch a browser for displaying a help page in HTML.
exec()有四个重载版本 There are four overloaded versions of the exec() command:
public Process exec(String command); public Process exec(String [] cmdArray);
public Process exec(String command, String [] envp); public Process exec(String [] cmdArray, String [] envp);
For each of these methods, a command -- and possibly a set of arguments -- is passed to an operating-system-specific function call. This subsequently creates an operating-system-specific process (a running program) with a reference to a Process class returned to the Java VM. The Process class is an abstract class, because a specific subclass of Process exists for each operating system. You can pass three possible input parameters into these methods: A single string that represents both the program to execute and any arguments to that program An array of strings that separate the program from its arguments An array of environment variables Pass in the environment variables in the form name=value. If you use the version of exec() with a single string for both the program and its arguments, note that the string is parsed using white space as the delimiter via the StringTokenizer class.
以上内容来自于网络。
关于java调用外部程序需要注意的事项
1. 当调用的外部命令中包含重定向(<、>),管道( | ) 命令时,exec(String command)的版本不能正确解析重定向、管道操作符。所以需要使用exec(String [] cmdArray)。
2.永远要在调用waitFor()方法之前读取数据流
永远要先从标准错误流中读取,然后再读取标准输出流
3.在exec()后 立即调用waitFor()会导致进程挂起。
java 调用windows 脚本:
先看下面的例子,该例子实现通过调用bat脚本打印“hellword”。代码如下: