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;
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
希望与广大网友互动??
点此进行留言吧!