Fullmenu null

 

23 August 2017

Sometimes we need to know which file is consuming the most disk space but because we have a big number of subdirectories is difficult to find. In certain operating systems it is "easy" to find it by concatenating several commands like du grep etc.

Through this script we will find the path of the file with the biggest size regardless the number of subdirectories

max=null

void scanDir( File dir ){
  dir.eachFile{ f->
    max = max && max.size() >= f.size() ? max : f
  }
  dir.eachDir{ d ->
    scanDir(d)
  }
}

scanDir(new File('.'))

println "El fichero mayor es: $max.path y ocupa ${max.size()} bytes"

We will explain in detail the content of our groovy script that has the function of finding the biggest file:

We define a function called scanDir responsible of traversing recursively all directories and subdirectories of the route indicated by parameter. Compare the size of each of the files that appear and will save the biggest.

To go through each of the directories and subdirectories of the route indicated by parameter, we use:

  dir.eachFile{ f->

To browse the files of the found directory/subdirectory, we use:

  dir.eachDir{ d ->

We make the comparison between the size of the different files using f.size () (this method returns the size of the file):

    max = max && max.size() >= f.size() ? max : f

To execute this process we simply call the scanDir function indicating the route we want to review (in this case .):

scanDir(new File('.'))

At the end of the process we will obtain the file from which we can obtain it route, size, etc.

println "El fichero mayor es: $max.path y ocupa ${max.size()} bytes"

Script
max=null

void scanDir( File dir ){
  dir.eachFile{ f->
    max = max && max.size() >= f.size() ? max : f
  }
  dir.eachDir{ d ->
    scanDir(d)
  }
}

scanDir(new File('.'))

println "El fichero mayor es: $max.path y ocupa ${max.size()} bytes"