如何使用Java运行OS命令

时间:2013-02-16 14:13:48

标签: java windows command cmd

我正在创建一个程序,必须使用clafer -m=xml Case5.cfr调用 Clafer

所以我用

ProcessBuilder pb = new ProcessBuilder("clafer -m=xml " + "Case5.cfr");
pb.directory(new File("C:\\Users\\unituser\\workspace\\com.unitbilisim.clafer2Ecore\\src\\model\\"));
Process P = pb.start();

但总是会出现以下错误:

Exception in thread "main" java.io.IOException: Cannot run program "clafer -m=xml Case5.cfr" (in directory "C:\Users\unituser\workspace\com.unitbilisim.clafer2Ecore\src\model"): CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at EmfCompare.emfCompareDeneme.main(emfCompareDeneme.java:54)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 2 more

我不明白为什么。任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

尝试

Process p = Runtime.getRuntime().exec("clafer -m=xml Case5.cfr", null, new File("C:\\Users\\unituser\\workspace\\com.unitbilisim.clafer2Ecore\\src\\model\\"));

Process p = new ProcessBuilder("clafer", "-m=xml", "Case5.cfr")
   .directory(new File("C:\\Users\\unituser\\workspace\\com.unitbilisim.clafer2Ecore\\src\\model\\"))
   .start();

答案 1 :(得分:0)

你可以用这个:

final Runtime rt = Runtime.getRuntime();
rt.exec("OS command");

修改 您也可以使用ProcessBuilder

检查this link以获取两者的示例