Obtain the utilization rate of hard disk, CPU and memory in LINUX by hard coding

Article directory

Environment introduction

System: Winning Qilin 7
jdk: 1.8

Problem description

In the process of localization and adaptation, the information of the utilization rate of system hard disk, cpu and memory needed to be used in the project;

processing method

1. Use sigar.jar to obtain;
2. Obtain system information by reading system configuration file;
The first method is to load libsigar-amd64-linux.so in some system environments under the domestic environment, which will report an error. Therefore, the second method is used for processing. The code is as follows

Specific code implementation

package com.xx.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONObject;

/**
 * Get system information
 * @createTime 2020 March 17th 2013
 */
public class LinuxProc {
	private static final String proc_stat = File.separator + "proc" + File.separator + "stat";
	private static final String proc_meminfo = File.separator + "proc" + File.separator + "meminfo";
	private static final String proc_diskinfo = "df -hl";
	private static final String home_path = "/home";
	private static final DecimalFormat def = new DecimalFormat("#.00");
	public static void main(String[] args){
		getSysResource();
	}
	public static void getSysResource() {
		Map<String, String> data = new HashMap<>();
		data.put("cpuUsedRate", getCpuTime());
		data.put("memUsedRate", getMemTime());
		data.put("diskUsedRate", getDiskUsage());
		data.put("diskInfo", home_path);
		System.out.println(JSONObject.fromObject(data));
	}

	private static String getCpuTime() {
		Map<String, Long> startTime = readCpuConfig();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		Map<String, Long> endTime = readCpuConfig();
		Double cpuUsage = new Double(0.0);
		long totalTime = endTime.get("totalTime") - startTime.get("totalTime");
		long startIdleTime = startTime.get("idleTime");
		long endIdleTime = endTime.get("idleTime");
		if (totalTime > 0) {
			cpuUsage = (1 - (((double) (endIdleTime - startIdleTime)) / totalTime)) * 100;
		}
		return def.format(cpuUsage);
	}

	private static String getMemTime() {
		try {
			String content = readFile(proc_meminfo);
			if ("".equals(content) || content == null) {
				return "0.00";
			}
			String[] contents = content.split("\n");
			long memTotal = 0L;
			long memFree = 0L;
			long buffers = 0L;
			long cached = 0L;
			if (contents.length > 0) {
				for (String val : contents) {
					if (val.startsWith("MemTotal:")) {
						memTotal = matchNum(val);
					}
					if (val.startsWith("MemFree:")) {
						memFree = matchNum(val);
					}
					if (val.startsWith("Buffers:")) {
						buffers = matchNum(val);
					}
					if (val.startsWith("Cached:")) {
						cached = matchNum(val);
					}
				}

			}
			// (1-(MemFree+Buffers+Cached)/MemTotal)*100
			Double memUsage = new Double(0.0);
			memUsage = (1 - ((double) (memFree + buffers + cached) / memTotal)) * 100;
			return def.format(memUsage);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "0.00";
	}

	private static long matchNum(String val) {
		Pattern pattern = Pattern.compile("[^0-9]");
		Matcher matcher = pattern.matcher(val);
		return Long.parseLong(matcher.replaceAll(""));
	}

	private static String readFile(String curfile) {
		File f = new File(curfile);
		try {
			if (!f.exists()) {
				return "";
			}
			FileReader cf = new FileReader(curfile);
			BufferedReader is = new BufferedReader(cf);
			String filecontent = "";
			String str = is.readLine();
			while (str != null) {
				filecontent += str;
				str = is.readLine();
				if (str != null)
					filecontent += "\n";
			}
			is.close();
			cf.close();
			return filecontent;
		} catch (Exception e) {
			System.err.println("Cannot read property file: " + curfile + " \n" + e.getMessage());
			return "";
		}
	}

	private static Map<String, Long> readCpuConfig() {
		Map<String, Long> cpuTimeMap = new HashMap<String, Long>();
		try {
			String content = readFile(proc_stat);
			if (content == null || "".equals(content)) {
				return cpuTimeMap;
			}
			long idleTime = 0L;
			long totalTime = 0L;
			String[] contents = content.split("\n");
			if (contents.length > 0) {
				String fristLine = contents[0];
				if (fristLine.startsWith("cpu ")) {
					String[] vals = fristLine.split(" ");
					if (vals.length >= 10) {
						// user nice system idle iowait irq softirp
						for (int i = 1; i <= 9; i++) {
							long v = Long.parseLong("".equals(vals[i].trim()) ? "0" : vals[i].trim());
							totalTime += v;
						}
						idleTime = Long.parseLong(vals[5]);
					}
				}
			}
			cpuTimeMap.put("idleTime", idleTime);
			cpuTimeMap.put("totalTime", totalTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cpuTimeMap;
	}

	private static String getDiskUsage() {
		try {
			Runtime runtime = Runtime.getRuntime();
			Process process = runtime.exec(proc_diskinfo);
			BufferedReader bufferedReader = null;
			try {
				bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
				String str = null;
				String[] strArray = null;
				while ((str = bufferedReader.readLine()) != null) {

					if (!str.contains(home_path)) {
						continue;
					}
					int m = 0;
					strArray = str.split(" ");
					for (String para : strArray) {
						if (para.trim().length() == 0) {
							continue;
						}
						++m;
						if (para.endsWith("%")) {
							if (m == 5) {
								return def.format(Double.parseDouble(para.replaceAll("%", "")));
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "0.00";
	}
}

157 original articles published, 100 praised, 840000 visitors+
His message board follow

Tags: Java JDK Linux JSON

Posted on Tue, 17 Mar 2020 10:06:57 -0400 by sethcox