JAVA 遍历文件夹下的所有文件(递归调用和非递归调用) - qyqingyan的专栏 - 博客频道 - CSDN.NET
非递归调用遍历文件夹:
- 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("文件夹:" + 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("文件夹:" + file2.getAbsolutePath());
- list.add(file2);
- fileNum++;
- } else {
- System.out.println("文件:" + file2.getAbsolutePath());
- folderNum++;
- }
- }
- }
- } else {
- System.out.println("文件不存在!");
- }
- System.out.println("文件夹共有:" + folderNum + ",文件共有:" + fileNum);
- }