简体   繁体   English

如何在Ruby中获取目录中文件的总大小

[英]How to get the total size of files in a Directory in Ruby

I am trying to copy some files into a directory using Ruby, i need to assure the files inside the directory not exceed 2GB. 我试图使用Ruby将一些文件复制到一个目录中,我需要确保目录中的文件不超过2GB。 is there any way to check the total size of files inside the directory. 有没有办法检查目录中的文件总大小。

Just mydir : 只是mydir

Dir['mydir/*'].select { |f| File.file?(f) }.sum { |f| File.size(f) }

mydir and all subdirectories: mydir和所有子目录:

Dir['mydir/**/*'].select { |f| File.file?(f) }.sum { |f| File.size(f) }

However, it's the sum of exact file sizes, not the space they occupy on the disk. 但是,它是确切文件大小的总和,而不是它们在磁盘上占用的空间。 For disk usage, this is more accurate: 对于磁盘使用,这更准确:

Dir['mydir/*'].select { |f| File.file?(f) }.sum { |f| File.stat(f).blocks * 512 }

For Unix-flavoured OS's, it may be easiest to simply shell out to the operating system to use the du command. 对于Unix风格的操作系统,简单地向操作系统发出外壳以使用du命令可能是最容易的。

For example 例如

du -bs #=> 1214674782

is the disk space in bytes consumed by my computer's current directory and its nested subdirectories. 是我的计算机的当前目录及其嵌套子目录消耗的磁盘空间(以字节为单位)。

du ../.rvm/src -bs #=> 722526755

is the same for a specified directory. 对于指定的目录是相同的。 Within Ruby, you can use the Kernel#system command: 在Ruby中,您可以使用Kernel#system命令:

s = system("du -bs") #=> 1214674782

To obtain the bytes consumed by the current directory only (and not nested subdirectories) remove "b" from the flags. 要获取当前目录所消耗的字节(而不是嵌套的子目录),请从标志中删除"b"

s = system("du -s") #=> 1301136

Note disk space consumption is somewhat more than the total of all file sizes, but that could be a better measure of what you are looking for. 注意磁盘空间消耗略高于所有文件大小的总和,但这可能更好地衡量您要查找的内容。

In Windows, You can use win32ole gem to calculate the same 在Windows中,您可以使用win32ole gem来计算相同的内容

 require 'win32ole'

 fso = WIN32OLE.new('Scripting.FileSystemObject')

 folder = fso.GetFolder('directory path')

  p folder.name

  p folder.size

 p folder.path

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM