栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java Process详解及实例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java Process详解及实例

Runtime

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

设置本地时间

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

 
  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命令获取网卡信息,两次获取网卡发送和接收数据包的信息,来计算网卡吞吐量。实现如下:

 
  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;
  }

  
  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;
  }

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/145440.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号