目标:
搜索盘符下面符合要求的文件名,并可以选择是否打开该文件
代码:
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class findQQ {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
File D = new File("D:"); //要搜索的磁盘
File[] files = D.listFiles();
System.out.println("请输入要查找的文件名:");
String filename = sc.next();
Arrays.stream(files).forEach(f -> new Find() {
@Override
public void Find_QQ(File file, String fileName){
if (file.isFile()) {
if (file.getName().equals(fileName)) {
System.out.println(file.getAbsolutePath());
System.out.println("是否启动?(y/n)");
if(sc.next().equals("y")){
try {
Runtime.getRuntime().exec(new String[] {"cmd","/c",file.getAbsolutePath()});
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("是否继续搜索?(y/n)");
if(sc.next().equals("n")) {
System.exit(0);
}
}
}
if (file.isDirectory()) {
File[] files1 = file.listFiles();
if (files1 != null && files1.length > 0) {
for (File f : files1) {
Find_QQ(f,fileName);
}
}
}
}
}.Find_QQ(f,filename));
System.out.println("没有找到该名称的文件!");
}
}
interface Find{
void Find_QQ(File file,String fileName) throws IOException, InterruptedException;
}
运行结果: