You need to enable JavaScript to run this app. Groovy实现多KB单位内存变量批量转换为可读单位的方法咨询
优惠活动
大模型
产品
解决方案
定价
更多

Groovy实现多KB单位内存变量批量转换为可读单位的方法咨询

实现技巧

你可以把已有的单变量转换逻辑封装为独立的复用方法,再通过集合批量管理所有待转换的内存指标,遍历调用转换方法即可实现批量输出,无需重复编写转换逻辑。

完整可运行代码

import java.text.DecimalFormat
import java.text.DecimalFormatSymbols

// 封装KB单位转人类可读格式的工具方法
String formatKbSize(long sizeInKb) {
    try {
        // 配置小数分隔符为逗号,匹配你需要的输出格式
        DecimalFormatSymbols symbols = new DecimalFormatSymbols()
        symbols.setDecimalSeparator(',' as char)
        DecimalFormat dec = new DecimalFormat("0.00", symbols)

        // 按单位量级从大到小判断,匹配到直接返回,无需执行全部判断逻辑
        double tb = sizeInKb / (1024 * 1024 * 1024)
        if (tb >= 1) {
            return dec.format(tb) + "TB"
        }
        double gb = sizeInKb / (1024 * 1024)
        if (gb >= 1) {
            return dec.format(gb) + "GB"
        }
        double mb = sizeInKb / 1024
        if (mb >= 1) {
            return dec.format(mb) + "MB"
        }
        return dec.format(sizeInKb) + "KB"
    } catch (Exception e) {
        println("单位转换失败,根因:" + e.getMessage())
        return "${sizeInKb}KB"
    }
}

// 替换为你从远程Linux主机获取的三个实际内存数值,单位均为KB
def totalMemKb = 5000000
def freeMemKb = 2000000
def availableMemKb = 3000000

// 用Map管理所有待输出的内存指标,key为输出前缀文本,value为对应的KB数值
def memoryMetrics = [
    "The total memory from this computer is: ": totalMemKb,
    "The total free from this computer is: ": freeMemKb,
    "The total Available from this computer is: ": availableMemKb
]

// 批量遍历转换并输出
memoryMetrics.each { outputPrefix, sizeKb ->
    println(outputPrefix + formatKbSize(sizeKb))
}

代码说明

  • 封装后的formatKbSize方法可以接收任意KB单位的数值,返回格式化后的可读字符串,可无限复用
  • 通过Map管理输出指标,后续如果需要新增其他内存相关的输出项,只需在Map中新增对应条目即可,无需修改转换逻辑
  • 调整了单位判断顺序,从最大的TB开始匹配,命中后直接返回,相比原有从KB开始判断的逻辑性能更优
  • 显式配置了小数分隔符为逗号,和你给出的输出示例格式完全匹配

内容的提问来源于stack exchange,提问作者Fabio Ochoa Restrepo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 13:45:09