文件大小可视化

import java.io.File

fun main() {
    val c = File("""C:\""")
    
    for (i in (c.listFiles()?:return)) {
        println("""
            |${ i.getAbsolutePath() }, 
            |${ when{i.isFile()->"文件"; i.isDirectory()->"目录"; else->"未知"} }, ${ i.getFileSize() }
            |""".trimMargin("|"))
    }
}

// 文件大小可视化
data class FileSize(val size: Double, val dw: String) {
    override fun toString() : String {
        var fsize: String = "%.2f".format(size)
        when {
            fsize.matches(""".*\.00$""".toRegex()) -> fsize = fsize.replace(".00", "")
            fsize.matches(""".*\.[1-9]0$""".toRegex()) -> fsize = fsize.replace("0$".toRegex(), "")
        }
        return "$fsize $dw"
    }
}

fun File.getFileSize() : FileSize? {
    val size = this.length().toDouble()
    return when {
        size in 1.0*1024 .. 1.0*1024*1024 -> FileSize(size/1024, "KB")
        size in 1.0*1024*1024 .. 1.0*1024*1024*1024 -> FileSize(size/1024/1024, "MB")
        size in 1.0*1024*1024*1024 .. 1.0*1024*1024*1024*1024 -> FileSize(size/1024/1024/1024, "GB")
        else -> FileSize(size, "Byte")
    }
}
C:\my_path_eve_var.txt, 
文件, 2.8 KB

C:\OEMSF, 
文件, 317.54 KB

C:\pagefile.sys, 
文件, 7.93 GB

C:\perflogs, 
目录, 0 Byte

C:\ping.jpg, 
文件, 1.51 MB

C:\Program Files, 
目录, 8 KB

你可能感兴趣的:(文件大小可视化)