文件夹的递归遍历
import java. io. File;
import java. util. ArrayList;
import java. util. List;
public class Test {
public static void main ( String[ ] args) {
File mFile = new File ( "D:\\英语单词" ) ;
List< File> dirList = new ArrayList < > ( ) ;
List< File> fileList = new ArrayList < > ( ) ;
diGuiDir ( mFile, dirList, fileList) ;
System. out. println ( "文件夹的数目: " + dirList. size ( ) ) ;
System. out. println ( "文件的数目: " + fileList. size ( ) ) ;
System. out. println ( "========[文件夹]========" ) ;
for ( File f : dirList) {
System. out. println ( f. getPath ( ) ) ;
}
System. out. println ( "========[文件]========" ) ;
for ( File f : fileList) {
System. out. println ( f. getPath ( ) ) ;
}
}
public static void diGuiDir ( File file, List< File> dirList, List< File> fileList) {
if ( file. isFile ( ) == true ) {
fileList. add ( file) ;
}
if ( file. isDirectory ( ) == true ) {
dirList. add ( file) ;
File[ ] fileArray = file. listFiles ( ) ;
if ( fileArray != null) {
for ( int x = 0 ; x < fileArray. length; x++ ) {
File f = fileArray[ x] ;
diGuiDir ( f, dirList, fileList) ;
}
}
}
}
}
02、文件夹的数据统计
案例代码
import java. io. File;
import java. util. *;
public class Demo {
public static void main ( String[ ] args) {
File mFile = new File ( "D:\\英语单词" ) ;
List< File> dirList = new ArrayList < > ( ) ;
List< File> fileList = new ArrayList < > ( ) ;
diGuiDir ( mFile, dirList, fileList) ;
Map< String, Integer> map = new HashMap < String, Integer> ( ) ;
for ( File f : fileList) {
String name = f. getName ( ) ;
String houzhui = name. substring ( name. lastIndexOf ( "." ) ) ;
if ( map. containsKey ( houzhui) == true ) {
Integer count = map. get ( houzhui) ;
count++ ;
map. put ( houzhui, count) ;
} else {
map. put ( houzhui, 1 ) ;
}
}
Set< Map. Entry< String, Integer> > set = map. entrySet ( ) ;
for ( Map. Entry< String, Integer> entry : set) {
String key = entry. getKey ( ) ;
Integer value = entry. getValue ( ) ;
System. out. println ( "文件类型: " + key + ",出现次数:" + value) ;
}
}
public static void diGuiDir ( File file, List< File> dirList, List< File> fileList) {
if ( file. isFile ( ) == true ) {
fileList. add ( file) ;
}
if ( file. isDirectory ( ) == true ) {
dirList. add ( file) ;
File[ ] fileArray = file. listFiles ( ) ;
if ( fileArray != null) {
for ( int x = 0 ; x < fileArray. length; x++ ) {
File f = fileArray[ x] ;
diGuiDir ( f, dirList, fileList) ;
}
}
}
}
}