Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Delete all files from a folder

I have been using a specific piece of code to delete files from a folder but it is proving very problematic because maybe I forgot to close an InputStream or two. The code I have is so big that I am not be able to see all the Inputstreams that I have not closed. Is there a way of deleting files whether there is an open InputStream or not?

This is the piece of the code that I have been using;

File fin = new File("C:/ABC Statements final/");
    File[] finlist = fin.listFiles();       
    for (int n = 0; n < finlist.length; n++) {
        if (finlist[n].isFile()) {
        System.gc();
        Thread.sleep(2000);
            finlist[n].delete();
        }
    }        

I have edited the code. This version works.

like image 908
Stanley Mungai Avatar asked Jul 12 '12 07:07

Stanley Mungai


People also ask

How do I force delete a folder in Windows 10?

To use this method, first, boot your Windows 10 or Windows 11 PC in safe mode using our guide. Once you're in safe mode, launch File Explorer and locate the folder to delete. Then, right-click this folder and choose “Delete.”

How do I force a folder to delete?

Press Shift + Delete to force delete a file or folder If the problem is due to the Recycle Bin, you can select the target file for folder, and press Shift + Delete keyboard shortcut to permanently delete it.

How do you force delete a file that won't delete?

One is simply using the delete option, and the other one is deleting files permanently. When you can't delete a file normally, you can delete undeletable files Windows 10 by selecting the target file or folder and then press Shift + Delete keys on the keyboard for a try.


1 Answers

There is no InputStream instances in the provided chunk of code.

To not write lots of untested IO code, please take a look at the apache.commons.io project. Especially at the FileDeleteStrategy class, for file deletion operations.

Your code might look like that:

File fin = new File("C:/ABC Statements final/");

for (File file : fin.listFiles()) {
    FileDeleteStrategy.FORCE.delete(file);
}   
like image 80
Dmytro Chyzhykov Avatar answered Sep 28 '22 06:09

Dmytro Chyzhykov