JAVA implements recursive and non recursive calls to of that traverse all files in the folder
- 2020-06-01 09:38:40
- OfStack
JAVA traverses all files in the folder (recursive and non-recursive)
1. Do not use recursive method calls.
public void traverseFolder1(String path) {
int fileNum = 0, folderNum = 0;
File file = new File(path);
if (file.exists()) {
LinkedList<File> list = new LinkedList<File>();
File[] files = file.listFiles();
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println(" folder :" + file2.getAbsolutePath());
list.add(file2);
fileNum++;
} else {
System.out.println(" file :" + file2.getAbsolutePath());
folderNum++;
}
}
File temp_file;
while (!list.isEmpty()) {
temp_file = list.removeFirst();
files = temp_file.listFiles();
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println(" folder :" + file2.getAbsolutePath());
list.add(file2);
fileNum++;
} else {
System.out.println(" file :" + file2.getAbsolutePath());
folderNum++;
}
}
}
} else {
System.out.println(" File does not exist !");
}
System.out.println(" Shared folders :" + folderNum + ", The file has :" + fileNum);
}
2. Use recursive method calls.
public void traverseFolder2(String path) {
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (files.length == 0) {
System.out.println(" The folder is empty !");
return;
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println(" folder :" + file2.getAbsolutePath());
traverseFolder2(file2.getAbsolutePath());
} else {
System.out.println(" file :" + file2.getAbsolutePath());
}
}
}
} else {
System.out.println(" File does not exist !");
}
}
3,
public static List<File> getFileList(String strPath) {
File dir = new File(strPath);
File[] files = dir.listFiles(); // The files in the file directory are all put into an array
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
if (files[i].isDirectory()) { // Determine whether it is a file or a folder
getFileList(files[i].getAbsolutePath()); // Gets the absolute path to the file
} else if (fileName.endsWith("avi")) { // Determine if the file name is valid .avi At the end
String strFileName = files[i].getAbsolutePath();
System.out.println("---" + strFileName);
filelist.add(files[i]);
} else {
continue;
}
}
}
return filelist;
}