How do I monitor the computer's CPU, memory, and disk usage in Java?

后端 未结 11 2835
粉色の甜心
粉色の甜心 2020-11-22 13:02

I would like to monitor the following system information in Java:

  • Current CPU usage** (percent)
  • Available memory* (free/total)
  • Available d

11条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 13:16

    The following code is Linux (maybe Unix) only, but it works in a real project.

        private double getAverageValueByLinux() throws InterruptedException {
        try {
    
            long delay = 50;
            List listValues = new ArrayList();
            for (int i = 0; i < 100; i++) {
                long cput1 = getCpuT();
                Thread.sleep(delay);
                long cput2 = getCpuT();
                double cpuproc = (1000d * (cput2 - cput1)) / (double) delay;
                listValues.add(cpuproc);
            }
            listValues.remove(0);
            listValues.remove(listValues.size() - 1);
            double sum = 0.0;
            for (Double double1 : listValues) {
                sum += double1;
            }
            return sum / listValues.size();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    
    }
    
    private long getCpuT throws FileNotFoundException, IOException {
        BufferedReader reader = new BufferedReader(new FileReader("/proc/stat"));
        String line = reader.readLine();
        Pattern pattern = Pattern.compile("\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)")
        Matcher m = pattern.matcher(line);
    
        long cpuUser = 0;
        long cpuSystem = 0;
        if (m.find()) {
            cpuUser = Long.parseLong(m.group(1));
            cpuSystem = Long.parseLong(m.group(3));
        }
        return cpuUser + cpuSystem;
    }
    

提交回复
热议问题