源碼:
public static String createFile(){ String cmd = "echo \"hhahah\" > F:\\aaa\\azzz.txt"; File file = new File("C:\\Windows\\System32"); StringBuilder result = new StringBuilder(); try { // 在單獨的進程中執行指定的字串命令 Process process = Runtime.getRuntime().exec(cmd); int execResult = process.waitFor(); System.out.println("執行結果:"+execResult); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = ""; while ((line = input.readLine()) != null) { System.out.println(line); result.append(line); } input.close(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("String結果是:"+result); return "";}public static void main(String[] args) { createFile();}
原來的程式如上,啟動並執行時候 報錯資訊如下:
java.io.IOException: Cannot run program "echo": CreateProcess error=2, 系統找不到指定的檔案。String結果是:at java.lang.ProcessBuilder.start(ProcessBuilder.java:1047)at java.lang.Runtime.exec(Runtime.java:617)at java.lang.Runtime.exec(Runtime.java:450)at java.lang.Runtime.exec(Runtime.java:347)at cn.huimin100.pay.center.service.support.util.Test.createFile(Test.java:22)at cn.huimin100.pay.center.service.support.util.Test.main(Test.java:42)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:147)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)... 10 more
說明,用java調用CMD 命令時,需要指定
即:調用的命令 需要指明是不是cmd 運行命令
修改:
String cmd = "cmd /c echo \"hhahah\" > F:\\aaa\\azzz.txt";
指明 cmd /c
註明:
Runtime.exec 方法建立一個本機進程,並返回 Process 子類的一個執行個體,該執行個體可用來控制進程並擷取相關資訊