Delete all files in directory (but not directory) - one liner solution

JavaFile IoApache Commons-Io

Java Problem Overview


I want to delete all files inside ABC directory.

When I tried with FileUtils.deleteDirectory(new File("C:/test/ABC/")); it also deletes folder ABC.

Is there a one liner solution where I can delete files inside directory but not directory?

Java Solutions


Solution 1 - Java

import org.apache.commons.io.FileUtils;

FileUtils.cleanDirectory(directory); 

There is this method available in the same file. This will also recursively deletes all sub-folders and files under them.

Docs: org.apache.commons.io.FileUtils.cleanDirectory

Solution 2 - Java

Do you mean like?

for(File file: dir.listFiles()) 
    if (!file.isDirectory()) 
        file.delete();

This will only delete files, not directories.

Solution 3 - Java

Peter Lawrey's answer is great because it is simple and not depending on anything special, and it's the way you should do it. If you need something that removes subdirectories and their contents as well, use recursion:

void purgeDirectory(File dir) {
	for (File file: dir.listFiles()) {
		if (file.isDirectory())
            purgeDirectory(file);
		file.delete();
	}
}

To spare subdirectories and their contents (part of your question), modify as follows:

void purgeDirectoryButKeepSubDirectories(File dir) {
	for (File file: dir.listFiles()) {
		if (!file.isDirectory())
            file.delete();
	}
}

Or, since you wanted a one-line solution:

for (File file: dir.listFiles())
    if (!file.isDirectory())
        file.delete();

Using an external library for such a trivial task is not a good idea unless you need this library for something else anyway, in which case it is preferrable to use existing code. You appear to be using the Apache library anyway so use its FileUtils.cleanDirectory() method.

Solution 4 - Java

Java 8 Stream

This deletes only files from ABC (sub-directories are untouched):

Arrays.stream(new File("C:/test/ABC/").listFiles()).forEach(File::delete);

This deletes only files from ABC (and sub-directories):

Files.walk(Paths.get("C:/test/ABC/"))
                .filter(Files::isRegularFile)
                .map(Path::toFile)
                .forEach(File::delete);

^ This version requires handling the IOException

Solution 5 - Java

Or to use this in Java 8:

try {
  Files.newDirectoryStream( directory ).forEach( file -> {
    try { Files.delete( file ); }
    catch ( IOException e ) { throw new UncheckedIOException(e); }
  } );
}
catch ( IOException e ) {
  e.printStackTrace();
}

It's a pity the exception handling is so bulky, otherwise it would be a one-liner ...

Solution 6 - Java

public class DeleteFile {
    public static void main(String[] args) {
        String path="D:\test"; 
        File file = new File(path);
        File[] files = file.listFiles(); 
        for (File f:files) 
        {if (f.isFile() && f.exists) 
            { f.delete();
system.out.println("successfully deleted");
            }else{
system.out.println("cant delete a file due to open or error");
} }  }}

Solution 7 - Java

rm -rf was much more performant than FileUtils.cleanDirectory.

Not a one-liner solution but after extensive benchmarking, we found that using rm -rf was multiple times faster than using FileUtils.cleanDirectory.

Of course, if you have a small or simple directory, it won't matter but in our case we had multiple gigabytes and deeply nested sub directories where it would take over 10 minutes with FileUtils.cleanDirectory and only 1 minute with rm -rf.

Here's our rough Java implementation to do that:

// Delete directory given and all subdirectories and files (i.e. recursively).
//
static public boolean clearDirectory( File file ) throws IOException, InterruptedException {

	if ( file.exists() ) {

		String deleteCommand = "rm -rf " + file.getAbsolutePath();
		Runtime runtime = Runtime.getRuntime();

		Process process = runtime.exec( deleteCommand );
		process.waitFor();

		file.mkdirs(); // Since we only want to clear the directory and not delete it, we need to re-create the directory.

		return true;
	}

	return false;

}

Worth trying if you're dealing with large or complex directories.

Solution 8 - Java

For deleting all files from directory say "C:\Example"

File file = new File("C:\\Example");      
String[] myFiles;    
if (file.isDirectory()) {
    myFiles = file.list();
    for (int i = 0; i < myFiles.length; i++) {
        File myFile = new File(file, myFiles[i]); 
        myFile.delete();
    }
}

Solution 9 - Java

Another Java 8 Stream solution to delete all the content of a folder, sub directories included, but not the folder itself.

Usage:

Path folder = Paths.get("/tmp/folder");
CleanFolder.clean(folder);

and the code:

public interface CleanFolder {
	static void clean(Path folder) throws IOException {
		
		Function<Path, Stream<Path>> walk = p -> {
			try { return Files.walk(p);
		} catch (IOException e) {
			return Stream.empty();
		}};
		
		Consumer<Path> delete = p -> {
			try {
				Files.delete(p);
			} catch (IOException e) {
			}
		};
		
		Files.list(folder)
			.flatMap(walk)
			.sorted(Comparator.reverseOrder())
			.forEach(delete);
	}
}

The problem with every stream solution involving Files.walk or Files.delete is that these methods throws IOException which are a pain to handle in streams.

I tried to create a solution which is more concise as possible.

Solution 10 - Java

I think this will work (based on NonlinearFruit previous answer):

Files.walk(Paths.get("C:/test/ABC/"))
                .sorted(Comparator.reverseOrder())
                .map(Path::toFile)
                .filter(item -> !item.getPath().equals("C:/test/ABC/"))
                .forEach(File::delete);

Cheers!

Solution 11 - Java

package com;
import java.io.File;
public class Delete {
    public static void main(String[] args) {

        String files; 
        File file = new File("D:\\del\\yc\\gh");
        File[] listOfFiles = file.listFiles(); 
        for (int i = 0; i < listOfFiles.length; i++) 
        {
            if (listOfFiles[i].isFile()) 
            {
                files = listOfFiles[i].getName();
                System.out.println(files);
                if(!files.equalsIgnoreCase("Scan.pdf"))
                {
                    boolean issuccess=new File(listOfFiles[i].toString()).delete();
                    System.err.println("Deletion Success "+issuccess);
                }
            }
        }
    }
}

If you want to delete all files remove

if(!files.equalsIgnoreCase("Scan.pdf"))

statement it will work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFahim ParkarView Question on Stackoverflow
Solution 1 - JavaReddyView Answer on Stackoverflow
Solution 2 - JavaPeter LawreyView Answer on Stackoverflow
Solution 3 - JavaChrissiView Answer on Stackoverflow
Solution 4 - JavaNonlinearFruitView Answer on Stackoverflow
Solution 5 - JavaChristian UllenboomView Answer on Stackoverflow
Solution 6 - JavaManbumihu ManavanView Answer on Stackoverflow
Solution 7 - JavaJoshua PinterView Answer on Stackoverflow
Solution 8 - JavaMahesh NarwadeView Answer on Stackoverflow
Solution 9 - JavahijackView Answer on Stackoverflow
Solution 10 - JavadansouzaView Answer on Stackoverflow
Solution 11 - JavaMaheshView Answer on Stackoverflow