Linux Shell,
find . -name "test" -type f
Java程序,
package com.oracle.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.Test;
public class FindFileTest {
public void findFile(String rootDir, List<String> files) {
File f = new File(rootDir);
if(f.isFile() && f.getName().equals("test")) {
files.add(f.getAbsolutePath());
}
File[] fSubs = f.listFiles();
if(fSubs == null || fSubs.length == 0) {
return;
}
for(File fSub: fSubs) {
findFile(fSub.getAbsolutePath(), files);
}
}
@Test
void testFindFile() {
String rootDir = System.getProperty("user.dir");
List<String> files = new ArrayList<String>();
findFile(rootDir, files);
System.out.println(files);
}
}
程序输出
Screen Shot 2019-04-26 at 6.50.15 AM.png
Python程序,
# coding:utf-8
import os
def findfile(dir,ls=[]):
child_dirs = os.listdir(dir)
for child_dir in child_dirs:
child_dir = dir + os.sep + child_dir
if os.path.isfile(child_dir) and os.path.basename(child_dir) == 'test':
ls.append(os.path.abspath(child_dir))
elif os.path.isdir(child_dir):
findfile(child_dir, ls)
if __name__ == '__main__':
pwd = os.getcwd()
ls = []
findfile(pwd, ls)
print(ls)
程序输出,
Screen Shot 2019-04-26 at 7.21.26 AM.png