Recursively getting the size of a directory

2019-06-17 11:59发布

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.

6条回答
我想做一个坏孩纸
2楼-- · 2019-06-17 12:28

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
查看更多
Anthone
3楼-- · 2019-06-17 12:28

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

查看更多
Rolldiameter
4楼-- · 2019-06-17 12:31

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

查看更多
唯我独甜
5楼-- · 2019-06-17 12:34

This seems to work:

Dir.glob(File.join(dir, '**', '*'))
  .map{ |f| File.size(f) }
  .inject(:+)
查看更多
▲ chillily
6楼-- · 2019-06-17 12:44

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'
查看更多
趁早两清
7楼-- · 2019-06-17 12:51

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).

查看更多
登录 后发表回答