1、java设置Linux系统时间之 System.getRuntime.exec()

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,那么它会集成它的父进程的环境变量,direxec返回的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命令介绍

 

3、具体代码实例:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值