タイトルの通り。
あるディレクトリ配下にディレクトリがいくつかあって、
その中で一番サイズが大きいディレクトリを知りたかったりしたい時とか。
def fileSize = { size, file ->
if (file.isDirectory()) {
file.eachFile {
size += owner.call(0, it)
}
} else {
size += file.size()
}
size
}
def fileListSize = { path ->
assert path != null
assert path.class != String.getClass()
def file = new File(path)
assert file.exists()
def map = [:]
if (file.isDirectory()) {
file.eachFile {
map.put(it.name, fileSize(0,it))
}
} else {
map.put(file.name, file.size())
}
map
}
/*
テスト用ディレクトリ構成
test
├a
│└aa.txt // 5byte
├b
│├ba.txt // 5byte
│└bb.txt // 6byte
├c
│├ca
││└caa.txt // 5yte
│├cb
││├cca.txt // 5byte
││└ccb.txt // 6byte
│├cc.txt // 5byte
│├cd.txt // 6byte
│└ce.txt // 7byte
└text.txt // 5byte
*/
assert fileSize(0, new File(/C:\work\filesize\test\text.txt/)) == 5
assert fileSize(0, new File(/C:\work\filesize\test\a/)) == 5
assert fileSize(0, new File(/C:\work\filesize\test\b/)) == 11
assert fileSize(0, new File(/C:\work\filesize\test\c/)) == 34
assert fileListSize(/C:\work\filesize\test\text.txt/) == ["text.txt":5]
assert fileListSize(/C:\work\filesize\test/) == ["a":5, "b":11, "c":34, "text.txt":5]
もっといい書き方ありそうだけど、いい案が浮かばず。。。
追記(2018/04/23)
サイズ順に並べて出力する。
fileListSize($/C:\work/$).sort{left, right -> left.value <=> right.value}.each {
println "${it.key} : ${String.format('%.2f', it.value/1024/1024)}MB"
}