【文件】从已知的路径中获取文件夹名称及遍历当前路径下的文件

import java.io.File;

public class test6 {
	public static void main(String[] args) {
		
		String dirPath1 = "F:\\git_repository\\github\\";
		String dirPath2 = "F:\\git_repository\\github\\README.md";
		File file = new File(dirPath1);
		
		/** 递归遍历所给路径下所有文件及文件夹 */
		showAllFiles(file);
		
		/** 获取当前路径下所有文件夹的名称 */
		showAllDirName(file);
		
		/** 获取当前路径的不同层次(1表示上一级;2表示上两级)目录下所有文件夹的名称 */
		int level = 3;//目录级别
		showUpAllDirName(dirPath1, level);
		
		
	}

	private static void showUpAllDirName(String dirPath1, int level) {
		File dir = new File(dirPath1);
		String parentPath = dir.getParent();
		level--;
		if(level == 0) {
			File parentDir = new File(parentPath);
			File[] files = parentDir.listFiles();
			for (File file : files) {
				if (file.isDirectory()) {
					System.out.println(file.getName());
				}
			}
		} else {
			showUpAllDirName(parentPath,level);
		}
	}

	private static void showAllDirName(File file) {
		File[] files = file.listFiles();
		for (File f : files) {
			if (f.isDirectory()) {
				System.out.println(f.getName());
			}
		}
	}

	private static void showAllFiles(File file) {
		File[] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			System.out.println(files[i].getAbsolutePath());
			try {
				if(files[i].isDirectory()) {
					showAllFiles(files[i]);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章