|
import java.io.File;
import java.util.Scanner;
public class FileSearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
File file_root[] = File.listRoots();
for(File info : file_root){
System.out.println(info.getPath());
}
System.out.print("请输入要遍历的盘:");
String path = sc.nextLine();
File file = new File(path);
while(!file.exists()){
file = null;
System.out.print("目录不存在,请重新输入:");
path = sc.nextLine();
file = new File(path);
}
boolean is=true;
while(is){
System.out.println("1.输出 目录下的所有文件和文件夹\t2.搜索指定文件\t3退出");
String key = sc.nextLine();
switch (key) {
case "1":
printFile(file);
break;
case "2":
System.out.print("请搜索要搜索的文件:");
String name = sc.nextLine();
printFile(file,name);
break;
case "3":
is=false;
break;
}
}
}
public static void printFile(File file){
File fileInfos[] = file.listFiles();
try {
for(File infos:fileInfos){
if(infos.isDirectory()){
System.out.println(infos.getPath());
printFile(infos);
}else{
System.out.println(infos.getPath());
}
}
} catch (NullPointerException e) {
}
}
public static void printFile(File file,String name){
File fileInfos[] = file.listFiles();
//这里最好try 不然可能会报错
try {
for(File infos:fileInfos){
if(infos.isDirectory()){
printFile(infos,name);
}else{
if(name.equals(infos.getName())){
System.out.println(infos.getPath());
}
}
}
} catch (NullPointerException e) {
//这儿不做处理
}
}
}
|
|