1. 程式人生 > >統計資料夾(包含子資料夾)中每種型別的檔案及個數

統計資料夾(包含子資料夾)中每種型別的檔案及個數

package com.lxq;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

/*
*分析以下需求,並用程式碼實現
	鍵盤錄入一個資料夾路徑,統計該資料夾(包含子資料夾)中,每種型別的檔案及個數,
		//獲取該路徑下所有檔案(包含子資料夾)
	
	注意:用檔案型別(字尾名,不包含.,"java","txt")作為key,用個數作為value,放入到map集合中,並按照如下格式列印map集合中的內容

		docx型別的檔案有  1 個
		java型別的檔案有  24 個
		txt型別的檔案有  10 個
		//...
 */


public class Demo1 {
	public static void main(String[] args) {
		//建立鍵盤錄入物件
		Scanner sc = new Scanner(System.in);
		//提示:
		System.out.println("請輸入一個你想查詢的路徑:");
		String path = sc.nextLine();
		//File的構造方法. 根據傳入的String路徑轉換成為File型別的物件
		File file = new File(path);
		//建立集合物件
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		//獲取了所有資料夾下的字尾名和出現次數 map中就有了資料
		getFileName(file, map);
		//遍歷map集合
		Set<Map.Entry<String, Integer>> entrys = map.entrySet();
		//得到鍵值對物件的集合 遍歷set集合得到每一個鍵值對物件
		for (Map.Entry<String, Integer> entry : entrys) {
			//獲得了每一個鍵值對物件後 可以獲取單個鍵值對的具體值
			String fileHouZui = entry.getKey();
			Integer num = entry.getValue();
			//輸出結果 docx型別的檔案有  1 個
			System.out.println(fileHouZui + "型別的檔案有"+num+"個");
		}
		
	}
	
	public static void getFileName(File file,HashMap<String, Integer> map){
		//獲取所有檔案
		//判斷檔案是否是一個資料夾
		if (file.isDirectory()) {
			//獲取資料夾的檔案陣列
			File[] files = file.listFiles();
			//遍歷檔案陣列
			for (File f : files) {
				//f是一個檔案
				if (f.isFile()) {
					//獲取這個檔案的檔名
					String filename = f.getName();
					//切割檔名
					String[] split = filename.split("\\.");
					//獲取字尾名
					String houZui = split[split.length - 1];
					//新增到集合中去
					//做判斷集合中是否出現過同名字尾
					if (map.get(houZui) == null) {
						//新增新的字尾
						map.put(houZui, 1);
					} else {
						//若出現過的字尾先獲取他出現的次數再讓他的次數+1
						Integer integer = map.get(houZui);
						integer++;
						//從新新增
						map.put(houZui, integer);
					}
				} else {//f是一個資料夾
					//遞迴 有一個獲取資料夾所有檔案的方法 並獲取他的字尾名
					getFileName(f,map);
				}
			}
		} else {
			//獲取檔名
			String filename = file.getName();
			//以.來切割檔名 獲得檔案的字尾(檔案的型別) Demo.java  [Demo,java]
			String[] split = filename.split("\\.");
			String houZui = split[split.length - 1];
			//判斷map集合中是否有重複的字尾
			if (map.get(houZui) == null) {
				//若沒有重複的key 說明這是第一次出現的字尾名 把這個字尾名新增到map集合中去 並給他的值賦值為1
				map.put(houZui, 1);
			} else {
				//根據map集合的鍵(檔案的字尾名)找值(字尾名出現的次數)
				Integer integer = map.get(houZui);
				//找到值(檔案字尾名出現的次數) 自增一次
				integer++;
				//把新的次數重新新增到集合中去
				map.put(houZui, integer);
			}
		}
	}
	
}