Two methods for recursively traversing the file name at the end of the specified suffix under the directory

When you begin to learn Java, you often try other ideas besides the correct answer. Although this so-called other ideas may not be the most resource-saving and may not be the most efficient method of code efficiency, it may deepen the beginners ’knowledge of Java Understand, the following are two methods for recursively traversing the file name at the end of the specified suffix in the directory.

Method 1: Use the listFile () method of the File class to traverse and obtain the file path for recursion (common method)

public static void main(String[] args) {
    findFile("d:/",".jpg");
}

public static void findFile(String path,String suffix) {
    File f = new File(path);
    if(f.isFile()) {
        if(f.getName().endsWith(suffix)) {
	    System.out.println(f.getName());
	};
    }else {
	File[] listFiles = f.listFiles();//通过listFiles方法获取元素为文件的数组
	if(listFiles!=null && listFiles.length>0) {
	    for(File f2:listFiles) {
	        findFile(f2.getAbsolutePath(),suffix);//遍历并获取文件的路径名字符串
	    };
	}	
    }
}

Method 2: Use the list () method of the File class to traverse and splice out a new file path for recursion

public static void main(String[] args) {
    findFile("d:/",".jpg");
}
public static void findFile(String path,String suffix) {
    File f = new File(path);
    if(f.isFile()) {
        if(f.getName().endsWith(suffix)) {
	    System.out.println(f.getName());
	};
    }else {
	String[] list = f.list();//通过list方法获取元素为文件名的数组
	if(list!=null && list.length>0) {
	    for(String name:list) {
		String path2 = path+name+"/";//遍历并拼接出文件的路径名字符串
		findFile(path2,suffix);
	    };
	}	
    }
}

 

Published 4 original articles · received 1 · views 187

Guess you like

Origin blog.csdn.net/joeychiang/article/details/105376250