Code ideas:
If you want to loop through all subfolders in a folder, you need to use recursion.
First, determine whether the path exists:
Yes: Get the file
Determine whether it is a folder:
Yes: Call yourself and continue to get the contents in the subfolder
No: determine the file suffix, if it matches it, it will be output.
No: Output prompt
package com.hanqi.maya.util;import java.io.File;import java.util.Scanner;public class TestGuolv { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Please enter the path to look for"); String s=sc.nextLine(); File file =new File(s); filesum(file,1); } public static void filesum(File f,int len){ if(f.exists()){//Judge whether the path exists in File[] files=f.listFiles(); //Get the file name under the path for(File fi:files){ //Cyclic output file name if(fi.isDirectory()){ //Judge whether the folder printBlank(len); System.out.println(fi.getName()+"folder"); filesum(fi,len+1); //Continue to call yourself}else{ printBlank(len); //Output space if(fi.getName().endsWith(".java")){//If it is a file, determine whether it is a ".java" suffix. If it is a "suffix", then output System.out.println(fi.getName()); } } } } } else{ System.out.println("File does not exist!!!"); } } public static void printBlank(int len){ for (int i = 0; i < len; i++) {//Output. to distinguish folder hierarchy System.out.print(". "); } }}Summary and questions:
I learned about all the files in the output folder yesterday, but today I made a slight change to find the files with the specified suffix under the folder.
Because there is no hierarchy when outputting, I wrote a loop to add spaces in front of the output file so that the levels are clear. Later, I found that the spaces are not clear enough for Chinese characters. When encountering Chinese characters, they will indent several spaces, but it will not be like this when using symbols.
There is also the problem of how to control the specified suffix name and has not been resolved.
The above article Java implements the simple file filter function is all the content I have shared with you. I hope you can give you a reference and I hope you can support Wulin.com more.