JAVA traverses all files in a folder (recursive call and non-recursive call)
JAVA traverses all files in a folder (recursive call and non-recursive call) call)
1. Method calls without recursion
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("文件:" + 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("文件:" + file2.getAbsolutePath()); folderNum++; } } } } else { System.out.println("File does not exist!"); } System.out.println("Total folder:" + folderNum + ",Total file:" + 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("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("文件:" + file2.getAbsolutePath()); } } } } else { System.out.println("File does not exist!"); } }
3. Determine the extension
public static List<File> getFileList(String strPath) { File dir = new File(strPath); File[] files = dir.listFiles(); // All files in the file directory are placed in 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()); // Get the absolute path of the file } else if (fileName.endsWith("avi")) { // Determine if the file name ends with .avi String strFileName = files[i].getAbsolutePath(); System.out.println("---" + strFileName); filelist.add(files[i]); } else { continue; } } } return filelist; }