rayman
rayman

Reputation: 21596

Prevent Dir deleting

the following code is deleting files and DIRS in a specific folder. How could I adjust it, so it will delete only the files in the folder but not the dirs inside

code:

            File folder = new File(path);
            File[] listOfFiles = folder.listFiles();
            if (listOfFiles != null)
            {
                for (int i = 0; i < listOfFiles.length; i++)
                {
                    logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
                    listOfFiles[i].delete();
                }
            }

thanks, ray.

Upvotes: 0

Views: 98

Answers (4)

sdolgy
sdolgy

Reputation: 7001

http://download.oracle.com/javase/6/docs/api/java/io/File.html#isDirectory()

 if (!listOfFiles[i].isDirectory()) { listOfFiles[i].delete(); } 

Upvotes: 0

Stephen C
Stephen C

Reputation: 718788

Easy ...

if (!listOfFiles[i].isDirectory()) {
    listOfFiles[i].delete();
}

FWIW - your current code will only delete empty subdirectories. According to the javadoc, deleting a directory that is non-empty will fail; i.e. return false.

Upvotes: 1

Nate
Nate

Reputation: 2881

        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();
        if (listOfFiles != null)
        {
            for (int i = 0; i < listOfFiles.length; i++)
            {                    
                if( !listOfFiles[i].isDirectory() ){   // if not a directory...
                    logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
                    listOfFiles[i].delete();
                }
            }
        }

Make sense? :)

Upvotes: 1

Nivas
Nivas

Reputation: 18334

You have to use File.isDirectory

if(!listOfFiles[i].isDirectory())
{
    logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
    listOfFiles[i].delete();
}

Upvotes: 0

Related Questions