Recursively getting the size of a directory

。_饼干妹妹 提交于 2019-12-08 19:10:56

问题


Is there a good gem for getting recursively calculated directory sizes? In unix, I can use du, but I want a library that absorbs the difference among OS.


回答1:


Looks like sys-filesystem handles this, but you'll need to do some math to convert the available blocks into bytes (by multiplying by block-size).




回答2:


This seems to work:

Dir.glob(File.join(dir, '**', '*'))
  .map{ |f| File.size(f) }
  .inject(:+)



回答3:


Could something like this work for you?

def directory_size(path)
  path << '/' unless path.end_with?('/')

  raise RuntimeError, "#{path} is not a directory" unless File.directory?(path)

  total_size = 0
  Dir["#{path}**/*"].each do |f|
    total_size += File.size(f) if File.file?(f) && File.size?(f)
  end
  total_size
end

puts directory_size '/etc'



回答4:


Here's my solution using http://ruby-doc.org/core-2.2.0/File.html#method-c-size:

def directory_size(path)
  size=0
  Dir.glob(File.join(path, '**', '*')) { |file| size+=File.size(file) }
  size
end



回答5:


Check out the File::Stat class (note that it does not calculate size of directory contents, it needs to be done manually).

file = File::Stat.new('.')
puts file.size

http://ruby-doc.org/core-1.9.3/File/Stat.html#method-i-size




回答6:


Support Tools:

diruse /M %windir%
diruse /K /S %windir%
diruse /S %windir%
diruse /, %windir%

Microsoft ... system install CD

msiexec /i %cd:~0,2%\SUPPORT\TOOLS\SUPTOOLS.MSI /q addlocal=all

Sysinternals Suite Utilities:

du.exe -l 1 %windir%

Microsoft ...

Sysinternals Suite



来源:https://stackoverflow.com/questions/9354595/recursively-getting-the-size-of-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!