public static boolean deleteDirectory ( String directory , boolean useOSNativeDelete ) throws IOException { boolean result = false ; if ( ! useOSNativeDelete ) { File dir = new File ( directory ) ; // first all files have to be cleared out for ( File file : dir . listFiles ( ) ) { if ( file . delete ( ) ) { log . debug ( "{} was deleted" , file . getName ( ) ) ; } else { log . debug ( "{} was not deleted" , file . getName ( ) ) ; file . deleteOnExit ( ) ; } file = null ; } // not you may remove the dir if ( dir . delete ( ) ) { log . debug ( "Directory was deleted" ) ; result = true ; } else { log . debug ( "Directory was not deleted, it may be deleted on exit" ) ; dir . deleteOnExit ( ) ; } dir = null ; } else { Process p = null ; Thread std = null ; try { Runtime runTime = Runtime . getRuntime ( ) ; log . debug ( "Execute runtime" ) ; //determine file system type if ( File . separatorChar == ' ' ) { //we are windows p = runTime . exec ( "CMD /D /C \"RMDIR /Q /S " + directory . replace ( ' ' , ' ' ) + "\"" ) ; } else { //we are unix variant p = runTime . exec ( "rm -rf " + directory . replace ( ' ' , File . separatorChar ) ) ; } // observe std out std = stdOut ( p ) ; // wait for the observer threads to finish while ( std . isAlive ( ) ) { try { Thread . sleep ( 250 ) ; } catch ( Exception e ) { } } log . debug ( "Process threads wait exited" ) ; result = true ; } catch ( Exception e ) { log . error ( "Error running delete script" , e ) ; } finally { if ( null != p ) { log . debug ( "Destroying process" ) ; p . destroy ( ) ; p = null ; } std = null ; } } return result ; }
Deletes a directory and its contents . This will fail if there are any file locks or if the directory cannot be emptied .