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;
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相关文章
EasyUi+Spring Data 实现按条件分页查询的实例代码
这篇文章主要介绍了EasyUi+Spring Data 实现按条件分页查询的实例代码,非常具有实用价值,需要的朋友可以参考下2017-07-07
SpringCloud使用Ribbon实现负载均衡的流程步骤
在微服务架构中,负载均衡是一项关键的技术,它可以确保各个服务节点间的负载分布均匀,提高整个系统的稳定性和性能,Spring Cloud 中的 Ribbon 就是一种负载均衡的解决方案,本文将深入探讨 Ribbon 的原理和在微服务中的应用,需要的朋友可以参考下2024-02-02
玩转spring boot 结合jQuery和AngularJs(3)
玩转spring boot,这篇文章主要介绍了结合jQuery和AngularJs,玩转spring boot,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-01-01


最新评论