Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. is there any way to check the total size of files inside the directory.

like image 869
Vaishakh K P Avatar asked Apr 17 '19 03:04

Vaishakh K P


People also ask

How do you find the size of the files from a directory?

Right-click the file and click Properties. The image below shows that you can determine the size of the file or files you have highlighted from in the file properties window. In this example, the chrome. jpg file is 18.5 KB (19,032 bytes), and that the size on disk is 20.0 KB (20,480 bytes).

How do I count the number of files in a directory in ruby?

using ruby how to get number of files in a given Directory,the file count should include count from recursive directories. Eg: folder1(2 files) -----> folder2(4 files) and folder2 is inside folder1. total count for above case should be 6 files.

How do I get the size of a file in Ruby?

length; var x = File(path). lengthSync();


3 Answers

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).then { |s| s.blocks * s.blksize } }
like image 78
Amadan Avatar answered Oct 18 '22 06:10

Amadan


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
like image 24
Ali Akbar Avatar answered Oct 18 '22 04:10

Ali Akbar


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.

like image 2
Cary Swoveland Avatar answered Oct 18 '22 05:10

Cary Swoveland