递归调用:遍历文件夹

估计这个题目在面试中也经常碰到:使用递归调用,遍历一个目录下的文件夹及文件,下面是一个简单代码,欢迎参考:
public class TestFile {
	

	public void getFiles(String path){
		File file = new File(path);
		File[] files = file.listFiles();
		for(File f: files){
			String fName = f.getName();
			if(!f.isFile()){
				System.out.println(f.getParent()+"\\"+fName);
				String newPath = f.getAbsolutePath();//返回绝对路径
				getFiles(newPath);
			}else{
				System.out.println(f.getParent()+"\\"+fName);
			}
		}
	}
	public static void main(String[] args) {
		//用户输入路径
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		String path;
		try {
			path = br.readLine();

			new TestFile().getFiles(path);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

希望对部分人有用。

猜你喜欢

转载自yulongxiang.iteye.com/blog/1980154