Java Process详解及实例
Runtime
Java可以通过Runtime来调用其他进程,如cmd命令,shell文件的执行等。可以应该该类设置系统时间,执行shell文件。此处记录几个有用应用如下。
设置本地时间
可以调用cmd/cdate命令,完成本地时间设置,不过这个命令在win7下可以使用,但是win10需要管理员权限,可能无法设置系统时间。win7下使用Java实现修改本地时间代码如下,需要注意的是waitFor是必须的,否则无法立即生效。
/**
*设置本地日期
*@paramdateyyyy-MM-dd格式
*/
privatestaticvoidsetSystemDate(Stringdate){
Processprocess=null;
Stringcommand1="cmd/cdate"+date;
System.out.println(command1);
try{
process=Runtime.getRuntime().exec(command1);
//必须等待该进程结束,否则时间设置就无法生效
process.waitFor();
}catch(IOException|InterruptedExceptione){
e.printStackTrace();
}finally{
if(process!=null){
process.destroy();
}
}
}
网卡吞吐量计算
可以通过cat/proc/net/dev命令获取网卡信息,两次获取网卡发送和接收数据包的信息,来计算网卡吞吐量。实现如下:
/**
*@Purpose:采集网络带宽使用量
*@paramargs
*@returnfloat,网络带宽已使用量
*/
publicstaticDoublegetNetworkThoughput(){
DoublecurRate=0.0;
Runtimer=Runtime.getRuntime();
//第一次采集流量数据
longstartTime=System.currentTimeMillis();
longtotal1=calculateThoughout(r);
//休眠1秒后,再次收集
try{
Thread.sleep(1000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
//第二次采集流量数据
longendTime=System.currentTimeMillis();
longtotal2=calculateThoughout(r);
//计算该段时间内的吞吐量:单位为Mbps(millionbitpersecond)
doubleinterval=(endTime-startTime)/1000;
curRate=(total2-total1)*8/1000000*interval;
System.out.println("收集网络带宽使用率结束,当前设备的网卡吞吐量为:"+(curRate)+"Mbps.");
returncurRate;
}
/**
*计算某个时刻网卡的收发数据总量
*@paramruntime
*@return
*/
privatestaticlongcalculateThoughout(Runtimeruntime){
Processprocess=null;
Stringcommand="cat/proc/net/dev";
BufferedReaderreader=null;
Stringline=null;
longtotal=0;
try{
process=runtime.exec(command);
reader=newBufferedReader(newInputStreamReader(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|IOExceptione){
e.printStackTrace();
}finally{
if(reader!=null){
try{
reader.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
if(process!=null){
process.destroy();
}
}
returntotal;
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!