1、介绍
Runtime.getRuntime()返回当前应用程序的Runtime对象,单例的。
Process Runtime.getRuntime.exec(String command);
command:要运行的命令,如:windows:”cmd /c dir”;Linux:”ls -a”。
直接运行字符串命令
Process Runtime.getRuntime.exec(String [] cmdArray);
cmdarray是要执行的本地命令集合。
运行这个本地命令集合。应用场景:用来动态的向已经写好的shell脚本中传递参数。例如:
String[] command = new String[]{"sudo","./setDate.sh","2010-10-10","12:12:12"};
Process proc = Runtime.getRuntime().exec(command);
在Linux普通用户环境中,传入时间参数"2010-10-10","12:12:12"到setDate.sh中,通过setDate.sh将传入的时间设置为Linux系统时间。
当然,还可以用这种方法:将command构建为一个字符串:"sudo ./setDate.sh 2010-10-10 12:12:12",使用exec(String command);实现相同的效果。
Process Runtime.getRuntime.exec(String command, String [] envp);
Process Runtime.getRuntime.exec(String [] cmdArray, String [] envp);
envp:当前的环境变量。如:“-Djava.library.path=/home/file/” (jni编码,将dll/so文件注册当前的环境变量中。Java -Djava.library.path=/home/file/ TestJni)
例如:
Process test = rt.exec(new String[] { "cmd /c", "TestShell.bat", "1stArg=alpha", "2ndArg=beta ", "3rdArg=/"333 echo/"" });
envp会被识别为:
1stArg=alpha
2ndArg=beta
echo
因为Java标准库给“=“右边的参数的头尾加了引号。也就是说原本给进去的参数是:name="value"的话,被处理了之后就变成:"name=""value"",所以编码的时候不可以写成"3rdArg=/"333 echo/""样式,否则从echo前面被截断了,而且引号也不见了
Process Runtime.getRuntime.exec(String cmdArray, String [] envp, File dir);
Process Runtime.getRuntime.exec(String [] cmdArray, String [] envp, File dir);
Runtime类中有很多exec方法,参数不同,但是最后都会调用exec(String[] cmdarray, String[] envp, File dir) 这个方法.
cmdarray是要执行的本地命令集合,envp是环境变量,如果envp is null,那么它会集成它的父进程的环境变量,dir是exec返回的Process的工作目录。
参考网页:http://www.javaeye.com/problems/9241
2、获取流
先看代码,
Process proc = Runtime.getRuntime().exec("date");
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
// BufferedInputStream bis = new
// BufferedInputStream(proc.getInputStream());
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
将运行的流结果获取
4、下一部分预告:
Linux shell脚本setDate.sh编写,与相关Linux命令介绍