乐趣区

关于java:Java获取Linux硬盘存储空间信息

通过解析 df 命令内容实现,获取以下信息:

[root@localhost ~]# df
Filesystem     1K-blocks      Used Available Use% Mounted on
devtmpfs        16324812         0  16324812   0% /dev
tmpfs           16342248         0  16342248   0% /dev/shm
tmpfs           16342248    271464  16070784   2% /run
tmpfs           16342248         0  16342248   0% /sys/fs/cgroup
/dev/sda3      451151536 201744672 226419856  48% /
/dev/sda1         999320    169864    760644  19% /boot
tmpfs            3268448         0   3268448   0% /run/user/0

实现代码:

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DiskUtils {

    @Data
    public static class Df {
        private String filesystem;
        private String blocks;
        /** 已应用 */
        private long used;
        /** 残余可用 */
        private long available;
        /** 已使用率,0-100 的整数值 */
        private int useRate;
        /** 挂载目录,'/' 示意挂载在根目录 */
        private String mountedOn;
    }

    public static Df df(String dir) {switch (OS.platform()) {
            case WINDOWS:
                Df df = new Df();
                df.setAvailable(Long.MAX_VALUE);
                return df;
        }

        Process process;
        try {log.debug("df" + dir);
            process = Runtime.getRuntime().exec("df" + dir);
            InputStream inputStream = process.getInputStream();
            // Filesystem      1K-blocks       Used Available Use% Mounted on
            // /dev/sdc       5814186096 5814169712         0 100% /home/spy-sd/sdc
            List<String> lines = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);

            List<String> titles = getTitles(lines.get(0));
            String[] values = lines.get(1).split("\\s+");
            Df df = new Df();
            for(int i = 0; i < titles.size(); i ++) {String title = titles.get(i);
                switch (title.toLowerCase()) {case "filesystem": df.setFilesystem(values[i]);break;
                    case "1k-blocks": df.setBlocks(values[i]);break;
                    case "used": df.setUsed(Long.parseLong(values[i]));break;
                    case "available": df.setAvailable(Long.parseLong(values[i]));break;
                    case "use%": df.setUseRate(Integer.parseInt(values[i].replace("%", "")));break;
                    case "mountedon": df.setMountedOn(values[i]);break;
                }
            }
            return df;
        } catch (IOException e) {e.printStackTrace();
            return null;
        }
    }

    private static List<String> getTitles(String titlesLine) {List<String> titles = new ArrayList<>();
        String[] titleArray = titlesLine.split("\\s+");
        for(String title: titleArray) {if(title.equalsIgnoreCase("on")) {if(!titles.isEmpty()) {int lastIdx = titles.size() - 1;
                    titles.set(lastIdx, titles.get(lastIdx) + "On");
                }
            } else {titles.add(title);
            }
        }
        return titles;
    }

    public static void main(String[] args) {Df df = df(new File("/home/spy-sd/sdc").getAbsolutePath());
        log.debug("df={}", df);
    }
}

Df 数据示例:

DiskUtils.Df(filesystem=/dev/sdc, blocks=5814186096, used=1652962708, available=3868180876, useRate=30, mountedOn=/home/spy-sd/sdc)
退出移动版