【文件】從已知的路徑中獲取文件夾名稱及遍歷當前路徑下的文件

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();
			}
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章