$ cc test.c -o test (译者注:对于linux用户,可以用gcc test.c ?o test,对应windows用户可以用相应的c语言编译程序编译成可执行程序test.exe) (你的 C 编译器可能要求不同的参数)然后使用下面的代码调用那个程序:
import java.io.*; import java.util.ArrayList;
public class ExecDemo { static public String[] runCommand(String cmd) throws IOException {
// set up list to capture command output lines
ArrayList list = new ArrayList();
// start command running
Process proc = Runtime.getRuntime().exec(cmd); /**译者注:前面的声明应该改成java.lang.Process,即: java.lang.Process proc = Runtime.getRuntime().exec(cmd); 假如不改的话可能编译不同通过,在译者的机器上使用jdk1.2,编译出现5个错误 使用jdk1.4编译出现4个错误 */ // get command´s output stream and // put a buffered reader input stream on it
InputStream istr = proc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(istr));
// read output lines from command
String str; while ((str = br.readLine()) != null) list.add(str);
public class DumpFiles { public static void main(String args[]) { String list[] = new File(".").list(); for (int i = 0; i < list.length; i++) System.out.println(list); } }
给出当前目录下所有文件和目录的列表。因此在大多情况下,使用ls/dir 可能没有意义。 使使用Runtime.exec有意义的一个情况就是答应用户指定一个编辑器或者文字处理程序(就像Emacs 或者 Vi 或者Word) 编辑文件。这是大型程序的一个通常的特性。程序将有一个配置文件指定编辑器的本地路径,然后使用这个路径调用Runtime.exec。 Runtime.exec 的一个微妙的地方就是它如何查找文件。例如,你使用: