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

Do you mean like?

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

This will only delete files, not directories.


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


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.