I am trying to copy some files into a directory using Ruby, i need to assure the files inside the directory not exceed 2GB. is there any way to check the total size of files inside the directory.
Just mydir
:
Dir['mydir/*'].select { |f| File.file?(f) }.sum { |f| File.size(f) }
mydir
and all subdirectories:
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.
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:
s = system("du -bs") #=> 1214674782
To obtain the bytes consumed by the current directory only (and not nested subdirectories) remove "b"
from the flags.
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
require 'win32ole'
fso = WIN32OLE.new('Scripting.FileSystemObject')
folder = fso.GetFolder('directory path')
p folder.name
p folder.size
p folder.path
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.