实现磁盘搜索文件

来源:互联网 发布:js 100 7 编辑:程序博客网 时间:2024/04/26 12:10

主要思路:

利用栈遍历计算机所有磁盘,得到计算机上所有的文件夹名和文件名,并将其写入txt文件,然后根据文件名和文件夹名在txt中进行搜索,得到其路径。这样,虽然在第一次将文件名和文件夹名写入到txt中要耗费时间,但以后查询就很方便了。

代码如下:

package sdu.out.searchfile;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.Stack;

/*此类用于将计算机内所有文件名和文件夹名写入txt中*/


public class Search {


public static void main(String[] args) throws IOException {
// String message = "请输入要搜索的文件名:";
// System.out.println(message);
// Scanner scanner = new Scanner(System.in);
// String fileName = scanner.next();
FileWriter fw = new FileWriter(new File("F:\\1.txt"), true);
Stack<String> folderStack = new Stack<String>();// 存放文件夹的临时栈
Stack<String> index = new Stack<String>();// 存放文件夹的临时栈
File[] roots = File.listRoots();// 获取所有磁盘盘符
for (int i = roots.length - 1; i >= 0; i--)
folderStack.push(roots[i].toString());


while (!folderStack.isEmpty())// 遍历
{
File[] fl = new File(folderStack.pop()).listFiles();
if (fl == null)
continue;
for (int i = 0; i < fl.length; i++) {
if (fl[i].isDirectory()) {
folderStack.push(fl[i].getAbsolutePath());
index.add(fl[i].getAbsolutePath());


} else {


index.add(fl[i].getAbsolutePath());
}
fw.write(fl[i].getAbsolutePath() + "\r\n");
}


}
fw.flush();
fw.close();
// while (!index.isEmpty())// 遍历
// {
// if (index.peek().endsWith(fileName)) {//这里搜索以filename结尾的文件,大家可以使用正则表达式搜索想要的文件
// System.out.println(index.peek());
// }
// index.pop();
// // System.out.println(index.pop());
// }
}


}




package sdu.out.searchfile;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/*此类用于在txt中搜索并得到想要找到的文件的路径*/
public class SearchInTxt {


public static void main(String[] args) throws IOException {
String message = "请输入要搜索的文件名:";
System.out.println(message);
Scanner scanner = new Scanner(System.in);
String fileName = scanner.nextLine();

File file = new File("F:/1.txt");

FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String str = null;
while((str=br.readLine())!=null){
if(str.endsWith(fileName)){
System.out.println(str);
}
}
}


}

0 0
原创粉丝点击