以下方法在Windows中啓動cmd
,它接受需要運行的命令的參數。在使用java的Windows中啓動cmd時出錯?
我已經使用以下命令測試了此方法:net users
並且它工作正常,並且它打印了用戶帳戶。但如果我運行dir
命令我碰到下面的錯誤:
java.io.IOEXception:
Cannot run program "dir": CreateProcess error=2, The system cannot find the file specified (in java.lang.ProcessBuilder)
代碼:
private String commandOutPut;
public void startCommandLine(String s) throws IOException{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(s); // you might need the full path
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String commandOutPut;
while ((commandOutPut = br.readLine()) != null) {
this.commandOutPut = this.commandOutPut + "\n" + commandOutPut;
}
System.out.println(this.commandOutPut);
}
還好,但有可能同時運行兩個命令 – james 2015-02-10 14:42:34
一樣,如果我想瀏覽某個地方,然後exucaute另一個命令 – james 2015-02-10 14:44:38
可能是你可以像==>過程親=調用Runtime.getRuntime()。EXEC( 「cmd/c start cmd.exe/K \」cd d:/ && dir \「」); – 2015-02-11 07:04:01