Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 知乎專欄 | Search | Email

1.3. exec 運行shell

exec(String[] cmdarray, String[] envp, File dir)
Executes the specified command and arguments in a separate process with the specified environment and working directory.

那個dir就是調用的程序的工作目錄,這句其實還是很有用的。

Windows下調用程序
Process proc =Runtime.getRuntime().exec("file.exe");

Linux下調用程序就要改成下面的格式
Process proc =Runtime.getRuntime().exec("./file");

Windows下調用系統命令
String [] cmd={"cmd","/C","copy file1.txt file2.txt"};
Process proc =Runtime.getRuntime().exec(cmd);

Linux下調用系統命令就要改成下面的格式
String [] cmd={"/bin/sh","-c","ln -s file1 file2"};
Process proc =Runtime.getRuntime().exec(cmd);

Windows下調用系統命令並彈出命令行窗口
String [] cmd={"cmd","/C","start copy file1.txt file2.txt"};
Process proc =Runtime.getRuntime().exec(cmd);

Linux下調用系統命令並彈出終端窗口就要改成下面的格式
String [] cmd={"/bin/sh","-c","xterm -e ln -s file1 file2"};
Process proc =Runtime.getRuntime().exec(cmd);

還有要設置調用程序的工作目錄就要
Process proc =Runtime.getRuntime().exec("ls",null, new File("/bin"));