解決方案--java執行cmd命令ProcessBuilder--出錯Exception in thread "main" java.io.IOException: Cannot run progra

當我嘗試在java中經過ProcessBuilder運行window的cmd命令時出現錯誤:
   
   
   
   
public static void main(String [] args) throws IOException { ProcessBuilder builder = new ProcessBuilder(); Process process = builder.command("dir d:\\").start(); InputStream inputStream = process.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"gb2312")); String line = null; while((line = br.readLine()) != null) { System.out.println(line); }}
出錯以下:
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

即便我把第三行語句改成下面的,仍然出錯
   
   
   
   
Process process = builder.command("cmd.exe /c dir d:\\").start();

後來我看許多人都遇到這種狀況,可是沒有人說解決方案的,有人就直接放棄了:
因此我又試了各類方式,終於解決了這個問題,這兩種方案執行都沒有問題.提供給遇到這種問題的朋友一種參考
方法一:
   
   
   
   
public static void main(String [] args) throws IOException { ProcessBuilder builder = new ProcessBuilder(); List<String> list = new ArrayList<>(); list.add("cmd.exe"); list.add("/c"); list.add("dir"); list.add("d:\\"); Process process = builder.command(list).start(); InputStream inputStream = process.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"gb2312")); String line = null; while((line = br.readLine()) != null) { System.out.println(line); }}
方法二:
   
   
   
   
public static void main(String [] args) throws IOException { ProcessBuilder builder = new ProcessBuilder(); Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("cmd.exe /c dir d:\\"); InputStream inputStream = process.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"gb2312")); String line = null; while((line = br.readLine()) != null) { System.out.println(line); }}
相關文章
相關標籤/搜索