Java-16.2

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.