2012-02-19 93 views
5

獲得遞歸計算的目錄大小是否有很好的寶石?在unix中,我可以使用du,但我想要一個吸收OS間差異的庫。遞歸獲取目錄的大小

+0

相關:http://stackoverflow.com/questions/3632074/what-is-the -fastest-way-to-calculate-disk-usage-per-customer – coreyward 2012-02-20 00:03:22

+1

相關:http://stackoverflow.com/questions/4508692/get-available-diskspace-in-ruby – coreyward 2012-02-20 00:06:19

回答

1

看起來像sys-filesystem可以處理這個問題,但是您需要做一些數學運算來將可用塊轉換爲字節(通過乘以塊大小)。

+2

這可能是由於自從很長一段時間以來這個答案,但mentio ned gem正確地確定了塊的大小(也是以字節爲單位的大小)。 'bytes_ {used,total,free}'只在文件系統(= mount)級別上,似乎不能確定目錄的大小。 – oliverguenther 2015-07-20 14:06:43

-1

查看File::Stat類(請注意,它不計算目錄內容的大小,它需要手動完成)。

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

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

+2

我假設你是downvoted,因爲它返回目錄的大小,但不是目錄內容的組合大小。 – d11wtq 2012-02-20 05:55:03

+0

啊,當然。這是一個令人失望的警告。 – fullsailor 2012-02-20 06:48:01

-2

支持工具:

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

微軟...系統安裝光盤

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

的Sysinternals Suite工具:

du.exe -l 1 %windir% 

微軟...

Sysinternals Suite

+0

目前還不清楚如何解決這個問題。 YOu需要解釋 – 2016-03-03 23:12:57

2

莫非這樣的事情對你的工作?

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' 
2

這似乎工作:

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

我想你實際上只是用'(&:size)'來獲取字符串的長度。你想要的是'{| file | File.size(file)}'。 – 2017-06-24 08:25:34

+0

@RyanLue你說得對,我確定了我的答案。 – yegor256 2017-06-25 12:16:01