Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a non-empty directory using the Dir class?

Tags:

ruby

Dir.delete("/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh")   

causes this error:

Directory not empty - /usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh

How to delete a directory even when it still contains files?

like image 906
Dhinesh Avatar asked May 16 '11 09:05

Dhinesh


People also ask

How do I delete a non empty directory?

The non-empty directory means the directory with files or subdirectories. We can delete the directory by using the Delete() method of the Directory class.

How do I delete a non empty directory in Java?

In Java, to delete a non-empty directory, we must first delete all the files present in the directory. Then, we can delete the directory. In the above example, we have used the for-each loop to delete all the files present in the directory.


2 Answers

Is not possible with Dir (except iterating through the directories yourself or using Dir.glob and deleting everything).

You should use

require 'fileutils' FileUtils.rm_r "/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh" 
like image 64
J-_-L Avatar answered Sep 22 '22 07:09

J-_-L


When you delete a directory with the Dir.delete, it will also search the subdirectories for files.

Dir.delete("/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh") 

If the directory was not empty, it will raise Directory not empty error. For that ruby have FiltUtils.rm_r method which will delete the directory no matter what!

require 'fileutils' FileUtils.rm_r "/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh" 
like image 36
Hitesh Avatar answered Sep 18 '22 07:09

Hitesh