1. 程式人生 > 實用技巧 >Java掃描磁碟遍歷檔案

Java掃描磁碟遍歷檔案

JavaScanDisk

Java掃描磁碟檔案。預設C盤,遍歷所有檔案

通過File類實現防毒軟體的掃描功能
要求:
1、通過控制檯輸入獲取需要掃描的目錄
提示: 1、全盤掃描 2、指定目錄掃描
如果選擇1:執行c盤全盤掃描,在控制檯打印出當時掃描的檔案路徑。
如果選擇2:提示:請輸入掃描路徑,並且列印掃描路徑
2、但掃描結束後提示:請選擇操作:1、繼續掃描 2、退出程式
如果選擇1: 就回到第一不
如果選擇2:就結束程式 System.exit(0);# JavaScanDisk
掃描類:


import java.io.File;
import java.util.Scanner;


public class Scan {

	public void allScan(File f) {
		// 將傳入的File物件變成File陣列
		File[] lf = f.listFiles();
		// 如果為空則結束這次方法。避免空指標異常
		if (lf == null) {
			return;
		}
		// 迴圈遍歷lf中的每個File物件
		for (File f1 : lf) {
			// 如果當前遍歷到的這個File物件是資料夾
			if (f1.isDirectory()) {
				// 得到當前資料夾的路徑
				String path = f1.getAbsolutePath();
				// 重新呼叫當前方法,並傳入剛剛遍歷到的資料夾物件進去
				allScan(new File(path));
				// 如果當前File物件是一個檔案
			} else {
				// 輸出當前檔案的名稱
				System.out.println(f1.getName());
				// System.out.println(f1.getAbsolutePath());

			}
		}

		System.out.println("掃描結束~");
		// 遍歷完成以後呼叫isContinue()方法
		isContinue();

	}

	/**
	 * @Description:判斷是否繼續掃描
	 * @author LYL
	 * @date 2021-01-11 13:08:24
	 */
	public void isContinue() {
		System.out.println("請選擇操作:1、繼續掃描  2、退出程式");
		Scanner sc = new Scanner(System.in);
		int i = sc.nextInt();
		//如果使用者輸入的是1
		if (i == 1) {			
			//通過Main()方法判斷是否重新掃描
			Main main = new Main();
		} else if (i == 2) {
			//如果輸入2則直接退出
			System.exit(0);
		} else {
			//如果不按提示輸入則丟擲異常
			throw new RuntimeException("請輸入所提示的資料!");
		}
		sc.close();
	}

}

使用者互動類:

import java.io.File;
import java.util.Scanner;

class Main {

	/**  
	 * @Description: 使用者互動
	 * @author LYL
	 * @date 2021-01-11 11:00:16
	 */

	public Main() {
		System.out.println("掃描全盤還是掃描指定路徑?1、全盤  2、指定路徑");
		Scanner sc = new Scanner(System.in);
		int i = sc.nextInt();
		//建立Scan物件,以便呼叫掃描的方法
		Scan scan = new Scan();
		if(i==1){			
			scan.allScan(new File("c:/"));
			
		}else if(i==2) {
			System.out.println("請輸入指定路徑:(格式:'c:/user/xxx')");
			String path = sc.next();
			//將使用者輸入的路徑放入一個新的File物件中
			scan.allScan(new File(path));
		}
		sc.close();
		//結束後判斷是否繼續
		scan.isContinue();
		
	}
			

	

}

測試類

public class Test {

	/**  
	 * @Description: 測試類
	 * @author LYL
	 * @date 2021-01-11 11:22:40
	 */

	public static void main(String[] args) {
		//呼叫Main的構造方法時就會執行
		Main main = new Main();
		
	}

}