Java-16.2
In this section, we will discuss how to traverse folders.
1. recursively traverse the project's root directory
package com.ray.ch16;import java.io.File;public class Test {public static void showAllFiles(String path) {File root = new File(path);File[] files = root.listFiles();for (File file : files) {if (file.isDirectory()) {showAllFiles(file.getAbsolutePath());} else if (file.isFile()) {System.out.println(file.getAbsolutePath());}}}public static void main(String[] args) {showAllFiles(".");}}
Output:
(Because there are many, no output is available)
2. Add name control based on the above
package com.ray.ch16;import java.io.File;import java.util.regex.Pattern;public class Test {public static void showAllFiles(String path, String regex) {File root = new File(path);File[] files = root.listFiles();for (File file : files) {if (file.isDirectory()) {showAllFiles(file.getAbsolutePath(), regex);} else if (file.isFile()) {Pattern pattern = Pattern.compile(regex);if (pattern.matcher(file.getName()).matches()) {System.out.println(file.getAbsolutePath());}}}}public static void main(String[] args) {showAllFiles("F:\\ws101\\ThinkInJava", "[A-za-z]+.java");}}
Output:
(Because there are many, no output is available)
The above code control only outputs the java source file.
Summary: This section describes two examples of folder traversal.