java中process方法用处_Java Process详解及实例

runtime

java可以通过runtime来调用其他进程,如cmd命令,shell文件的执行等。可以应该该类设置系统时间,执行shell文件。此处记录几个有用应用如下。

设置本地时间

可以调用cmd /c date命令,完成本地时间设置,不过这个命令在win7下可以使用,但是win10需要管理员权限,可能无法设置系统时间。win7下使用java实现修改本地时间代码如下,需要注意的是waitfor是必须的,否则无法立即生效。

/**

* 设置本地日期

* @param date yyyy-mm-dd格式

*/

private static void setsystemdate(string date){

process process = null;

string command1 = "cmd /c date "+date;

system.out.println(command1);

try {

process = runtime.getruntime().exec(command1);

//必须等待该进程结束,否则时间设置就无法生效

process.waitfor();

} catch (ioexception | interruptedexception e) {

e.printstacktrace();

}finally{

if(process!=null){

process.destroy();

}

}

}

网卡吞吐量计算

可以通过cat /proc/net/dev命令获取网卡信息,两次获取网卡发送和接收数据包的信息,来计算网卡吞吐量。实现如下:

/**

* @purpose:采集网络带宽使用量

* @param args

* @return float,网络带宽已使用量

*/

public static double getnetworkthoughput() {

double currate = 0.0;

runtime r = runtime.getruntime();

// 第一次采集流量数据

long starttime = system.currenttimemillis();

long total1 = calculatethoughout(r);

// 休眠1秒后,再次收集

try {

thread.sleep(1000);

} catch (interruptedexception e) {

e.printstacktrace();

}

// 第二次采集流量数据

long endtime = system.currenttimemillis();

long total2 = calculatethoughout(r);

// 计算该段时间内的吞吐量:单位为mbps(million bit per second)

double interval = (endtime-starttime)/1000;

currate = (total2-total1)*8/1000000*interval;

system.out.println("收集网络带宽使用率结束,当前设备的网卡吞吐量为:"+(currate)+"mbps.");

return currate;

}

/**

* 计算某个时刻网卡的收发数据总量

* @param runtime

* @return

*/

private static long calculatethoughout(runtime runtime){

process process = null;

string command = "cat /proc/net/dev";

bufferedreader reader = null;

string line = null;

long total = 0;

try {

process = runtime.exec(command);

reader = new bufferedreader(new inputstreamreader(process.getinputstream()));

while ((line = reader.readline()) != null) {

line = line.trim();

// 考虑多网卡的情况

if (line.startswith("eth")) {

log.debug(line);

line = line.substring(5).trim();

string[] temp = line.split("\\s+");

total+=(long.parselong(temp[0].trim()));// receive

total+=(long.parselong(temp[8].trim()));// transmit

}

}

} catch (numberformatexception | ioexception e) {

e.printstacktrace();

} finally {

if (reader != null) {

try {

reader.close();

} catch (ioexception e) {

// todo auto-generated catch block

e.printstacktrace();

}

}

if (process != null) {

process.destroy();

}

}

return total;

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值