3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

指定されたフォルダ内にあるファイルのサイズ一覧を返す(ディレクトリは内部のファイルサイズ合計)

Last updated at Posted at 2012-12-26

タイトルの通り。
あるディレクトリ配下にディレクトリがいくつかあって、
その中で一番サイズが大きいディレクトリを知りたかったりしたい時とか。


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"
}
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?