java在指定目錄下執行dos命令或者bat檔案
阿新 • • 發佈:2022-05-04
直接看源程式吧
public static void main(String[] args) throws IOException { File dir = new File("D:\"); // String command="netstat -an"; String command = "c:\windows\system32\cmd.exe /c netstat -an"; Runtime r = Runtime.getRuntime(); Process p = r.exec(command, null, dir); BufferedReader br = new BufferedReader(new InputStreamReader(p .getInputStream())); StringBuffer sb = new StringBuffer(); String inline; while (null != (inline = br.readLine())) { sb.append(inline).append("n"); } System.out.println(sb.toString()); }
最重要的是exec方法中的幾個引數,可以動態的旨定執行的目錄,這樣如果想執行對應的命令那麼就只需要指定對應的目錄就可以了。