Java Runtime.exec()的使用

Sun的doc里其实说明还有其他的用法:
inurl:www.oracle.com+Java Runtime.exec
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("exefile");
Linux下调用程序就要改成下面的格式
Process proc =Runtime.getRuntime().exec("./exefile");
Windows下调用系统命令
String [] cmd={"cmd","/C","copy exe1 exe2"};
Process proc =Runtime.getRuntime().exec(cmd);
Linux下调用系统命令就要改成下面的格式
String [] cmd={"/bin/sh","-c","ln -s exe1 exe2"};
Process proc =Runtime.getRuntime().exec(cmd);
Windows下调用系统命令并弹出命令行窗口
String [] cmd={"cmd","/C","start copy exe1 exe2"};
Process proc =Runtime.getRuntime().exec(cmd);
Linux下调用系统命令并弹出终端窗口就要改成下面的格式
String [] cmd={"/bin/sh","-c","xterm -e ln -s exe1 exe2"};
Process proc =Runtime.getRuntime().exec(cmd);
还有要设置调用程序的工作目录就要
Process proc =Runtime.getRuntime().exec("exeflie",null, new File("workpath"));
当然最好的执行系统命令的方法就是写个bat文件或是shell脚本。然后调用,那样修改和实现就简点多了。

原文地址:https://www.cnblogs.com/sprinng/p/6704499.html