1.代码实现
package com. wpq. car. dto;
import java. io. File;
public class Test {
public static void main ( String[ ] args) {
File file = new File ( "D:\\TEST" ) ;
boolean result = deleteAll ( file) ;
System. out. println ( result== true ? "文件删除成功" : "文件删除失败" ) ;
}
public static boolean deleteAll ( File file) {
if ( file== null || ! file. exists ( ) ) {
System. out. println ( "文件不存在" ) ;
return false ;
}
File[ ] files = file. listFiles ( ) ;
for ( File f: files) {
if ( f. isDirectory ( ) ) {
System. out. println ( f. getName ( ) ) ;
deleteAll ( f) ;
} else {
System. out. println ( f. getName ( ) ) ;
f. delete ( ) ;
}
}
file. delete ( ) ;
return true ;
}
}
2.代码优化
package com. wpq. car. dto;
import java. io. File;
public class Test {
public static void main ( String[ ] args) {
File file = new File ( "D:\\TEST" ) ;
boolean result = deleteAll ( file) ;
System. out. println ( result== true ? "文件删除成功" : "文件删除失败" ) ;
}
public static boolean deleteAll ( File file) {
if ( file== null || ! file. exists ( ) ) {
System. out. println ( "文件不存在" ) ;
return false ;
}
File[ ] files = file. listFiles ( ) ;
for ( File f: files) {
boolean b= f. isDirectory ( ) == true ? deleteAll ( f) : f. delete ( ) ;
}
file. delete ( ) ;
return true ;
}
}
JAVA API中对File的delete方法的说明