Java如何获取系统CPU、内存、硬盘使用情况(仅限windows,Linux)

1.首先引入sigar依赖

        <dependency>
            <groupId>org.fusesource</groupId>
            <artifactId>sigar</artifactId>
            <version>1.6.4</version>
        </dependency>

2.需要引入sigar的动态链接库 ,Windows放在jdk的bin下,Linux放在usr/lib64下,https://pan.baidu.com/s/1MXCypf1yNYu75ZLP1mz0gA ,提取码 :tzx9

3.代码

import org.hyperic.sigar.*;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取系统CPU、内存、硬盘使用情况
 *
 * @author yanzy
 * @date 2019/1/16 9:45
 */
public class SystemInfo {

    public static void main(String[] args) {
        try {
            // Windows放在jdk的bin下,Linux放在usr/lib64下
            System.out.println("位置:" + System.getProperty("java.library.path"));
            SystemInfo systemInfo=new SystemInfo();
            System.out.println(systemInfo.getCpuUsage());
            System.out.println(systemInfo.getMemoryUsage());
            System.out.println(systemInfo.getDiskIoUsage());
            System.out.println(systemInfo.getDiskUsage());
            System.out.println(systemInfo.path());
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /**
     * 获取内存使用率
     *
     * @return java.lang.String
     * @author yanzy
     * @version 1.0
     * @date 2019/1/16 16:56
     */
    public String getMemoryUsage() throws SigarException {
        Sigar sigar = new Sigar();
        Mem mem = sigar.getMem();
        // 获取总内存数
        Long total = mem.getTotal() / 1024L;
        // 获取已使用内存数
        Long used = mem.getUsed() / 1024L;
        // 取到百分比
        Long percentile = total / 100;
        return "内存使用率:" + used / percentile + "%";
    }

    /**
     * 获取cpu使用率
     *
     * @return java.lang.String
     * @author yanzy
     * @version 1.0
     * @date 2019/1/16 16:57
     */
    public String getCpuUsage() throws SigarException {
        Sigar sigar = new Sigar();
        return "CPU的使用率:	" + CpuPerc.format(sigar.getCpuPerc().getCombined());
    }

    /**
     * 获取磁盘使用率
     *
     * @return java.util.List<java.lang.String>
     * @author yanzy
     * @version 1.0
     * @date 2019/1/16 16:57
     */
    public List<String> getDiskUsage() throws Exception {
        Sigar sigar = new Sigar();
        List<String> stringList = new ArrayList<>();
        FileSystem[] fslist = sigar.getFileSystemList();
        for (int i = 0; i < fslist.length; i++) {
            FileSystem fileSystem = fslist[i];
            FileSystemUsage usage = sigar.getFileSystemUsage(fileSystem.getDirName());
            double usePercent = usage.getUsePercent() * 100D;
            stringList.add(fileSystem.getDevName() + "磁盘的使用率:" + (int) usePercent + "%");
        }
        return stringList;
    }

    /**
     * 获取当前磁盘IO的使用情况
     *
     * @return java.lang.String
     * @author yanzy
     * @version 1.0
     * @date 2019/1/17 18:31
     */
    public String getDiskIoUsage() throws Exception {
        // 获取当前每秒的读写量
        long tempTotal = getTotalByte();
        Thread.sleep(1000);
        long total = getTotalByte();

        // 字节转成kb
        double cha = (double) (total - tempTotal) / 1024;
        // 转成MB,保留1位小数
        BigDecimal bigDecimal = new BigDecimal(cha / 1024);
        double value = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return "磁盘IO的使用情况:" + value + " MB/S";
    }

    /**
     * 获取当前磁盘IO的读写数量
     *
     * @return long
     * @author yanzy
     * @version 1.0
     * @date 2019/1/17 16:11
     */
    public long getTotalByte() {
        Sigar sigar = new Sigar();
        long totalByte = 0;
        try {
            FileSystem[] fslist = sigar.getFileSystemList();
            for (int i = 0; i < fslist.length; i++) {
                if (fslist[i].getType() == 2) {
                    FileSystemUsage usage = sigar.getFileSystemUsage(fslist[i].getDirName());
                    totalByte += usage.getDiskReadBytes();
                    totalByte += usage.getDiskWriteBytes();
                }
            }
        } catch (SigarException e) {
            e.printStackTrace();
        }
        return totalByte;
    }

    /**
     * 获取当前项目的磁盘使用情况
     *
     * @return java.lang.String
     * @author yanzy
     * @version 1.0
     * @date 2019/1/21 10:34
     */
    public String path() throws Exception {
        String path = getClass().getResource("/").getFile();
        if (path.contains("/") && path.contains(":")) {
            path = path.replace("/", "").substring(0, path.indexOf(":"));
        }

        for (String disk : this.getDiskUsage()) {
            if (disk.contains(path) || disk.contains("rootfs")) {
                return "当前服务所在磁盘的使用率:" + disk;
            }
        }
        return "未找到相应的磁盘";
    }

    /**
     * Linux下获取磁盘IO使用率
     *
     * @return float
     * @author yanzy
     * @version 1.0
     * @date 2019/1/17 10:07
     */
    public float getHdIOpPercent() {
        System.out.println("开始收集磁盘IO使用率");
        float ioUsage = 0.0f;
        Process pro = null;
        Runtime runtime = Runtime.getRuntime();
        try {
            String command = "iostat -d -x";
            pro = runtime.exec(command);
            BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            String line = null;
            int count = 0;
            while ((line = in.readLine()) != null) {
                if (++count >= 4) {
                    String[] temp = line.split("\\s+");
                    if (temp.length > 1) {
                        float util = Float.parseFloat(temp[temp.length - 1]);
                        ioUsage = (ioUsage > util) ? ioUsage : util;
                    }
                }
            }
            if (ioUsage > 0) {
                System.out.println("本节点磁盘IO使用率为: " + ioUsage);
                ioUsage /= 100;
            }
            in.close();
            pro.destroy();
        } catch (IOException e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            System.out.println("IoUsage发生InstantiationException. " + e.getMessage());
            System.out.println(sw.toString());
        }
        return ioUsage;
    }
}

不引用第三方依赖获取系统信息,https://blog.csdn.net/qq_39486119/article/details/100043309

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Java中的ManagementFactory类来获取系统CPU内存使用率。以下是获取系统CPU使用率的示例代码: ``` import java.lang.management.ManagementFactory; import com.sun.management.OperatingSystemMXBean; public class SystemInfo { public static void main(String[] args) { OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); double cpuLoad = operatingSystemMXBean.getSystemCpuLoad() * 100; System.out.println("CPU使用率: " + cpuLoad + "%"); } } ``` 以下是获取系统内存使用率的示例代码: ``` import java.lang.management.ManagementFactory; import com.sun.management.OperatingSystemMXBean; public class SystemInfo { public static void main(String[] args) { OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); long totalMemorySize = operatingSystemMXBean.getTotalPhysicalMemorySize(); long freePhysicalMemorySize = operatingSystemMXBean.getFreePhysicalMemorySize(); double memoryLoad = (totalMemorySize - freePhysicalMemorySize) * 100 / totalMemorySize; System.out.println("内存使用率: " + memoryLoad + "%"); } } ``` 以下是获取系统磁盘使用率的示例代码: ``` import java.io.File; import java.io.IOException; public class SystemInfo { public static void main(String[] args) throws IOException { File file = new File("/"); long totalSpace = file.getTotalSpace(); long freeSpace = file.getFreeSpace(); long usableSpace = file.getUsableSpace(); double diskLoad = (totalSpace - freeSpace) * 100 / totalSpace; System.out.println("磁盘使用率: " + diskLoad + "%"); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值