解决方案--java执行cmd命令ProcessBuilder--出错Exception in thread "main" java.io.IOException: Cannot run program "dir d:\": CreateProcess error=2(xjl456852原创)

当我尝试在java中通过ProcessBuilder运行window的cmd命令时出现错误:
  1. public static void main(String [] args) throws IOException {
  2. ProcessBuilder builder = new ProcessBuilder();
  3. Process process = builder.command("dir d:\\").start();
  4. InputStream inputStream = process.getInputStream();
  5. BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"gb2312"));
  6. String line = null;
  7. while((line = br.readLine()) != null) {
  8. System.out.println(line);
  9. }
  10. }
出错如下:
Exception in thread "main" java.io.IOException: Cannot run program "dir d:\": CreateProcess error=2, 系统找不到指定的文件。
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1047)
at com.xjl456852.processBuilder.ProcessBuilderTest.main(ProcessBuilderTest.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.io.IOException: CreateProcess error=2, 系统找不到指定的文件。
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:385)
at java.lang.ProcessImpl.start(ProcessImpl.java:136)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1028)
... 6 more

即使我把第三行语句改为下面的,仍然出错
  1. Process process = builder.command("cmd.exe /c dir d:\\").start();

后来我看许多人都遇到这种情况,但是没有人说解决方案的,有人就直接放弃了:
所以我又试了各种方式,终于解决了这个问题,这两种方案执行都没有问题.提供给遇到这种问题的朋友一种参考
方法一:
  1. public static void main(String [] args) throws IOException {
  2. ProcessBuilder builder = new ProcessBuilder();
  3. List<String> list = new ArrayList<>();
  4. list.add("cmd.exe");
  5. list.add("/c");
  6. list.add("dir");
  7. list.add("d:\\");
  8. Process process = builder.command(list).start();
  9. InputStream inputStream = process.getInputStream();
  10. BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"gb2312"));
  11. String line = null;
  12. while((line = br.readLine()) != null) {
  13. System.out.println(line);
  14. }
  15. }
方法二:
  1. public static void main(String [] args) throws IOException {
  2. ProcessBuilder builder = new ProcessBuilder();
  3. Runtime runtime = Runtime.getRuntime();
  4. Process process = runtime.exec("cmd.exe /c dir d:\\");
  5. InputStream inputStream = process.getInputStream();
  6. BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"gb2312"));
  7. String line = null;
  8. while((line = br.readLine()) != null) {
  9. System.out.println(line);
  10. }
  11. }




posted @ 2016-09-04 17:03  三杯两盏淡酒  阅读(22414)  评论(5编辑  收藏  举报