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;
/**
* @ClassName: Scan
* @Description: 掃描類
* @author LYL
* @date 2021-01-11 11:05:44
*/
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());
}
}
}
/**
* @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();
main.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 void 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:/"));
System.out.println("掃描結束");
} else if (i == 2) {
System.out.println("請輸入指定路徑:(格式:'c:/user/xxx')");
sc.nextLine();
String path = sc.nextLine();
// 將用戶輸入的路徑放入一個新的File對象中
scan.allScan(new File(path));
System.out.println("掃描結束");
} else {
throw new RuntimeException("請輸入所提示的數據!");
}
// 結束后判斷是否繼續
scan.isContinue();
}
}
測試類
public class Test {
/**
* @Description: 測試類
* @author LYL
* @date 2021-01-11 11:22:40
*/
public static void main(String[] args) {
Main main = new Main();
main.Main();
}
}