使用Java编写一个简易的本地文件的检索相关字的程序

来源:互联网 发布:windows网络编程 编辑:程序博客网 时间:2024/04/29 06:15

</pre>目的:编写一个可以查找本地指定文件下下所有文件中包含相关字的文件<p></p><p>我的初衷是为了在本地的代码库中快速的找到已经编写过的包含特定功能的文件,当然要要使用这个程序的话,你必须有一定的命名和良好的注释习惯</p><p>目前这个程序刚写成,暂能实现简单的检索功能,我也在不断的提升这个程序的功能和效率,持续优化和完善</p><p></p><p></p><p></p><p><pre name="code" class="java">package searchfilesum;import java.io.*;import java.util.ArrayList;import java.util.Scanner;public class Search {static String fileName = null;static String searchName = null;static Scanner input = new Scanner(System.in);public static void main(String[] args) throws IOException{// TODO Auto-generated method stubSystem.out.println("请输入要查找的文件夹:");fileName = input.nextLine();System.out.println("请输入要查找的关键字:");searchName = input.nextLine();SearchFile sf = new SearchFile(fileName,searchName);}}class SearchFile {String fileName;ArrayList list;//保存有相关字的文件路径String searchName;byte[] by;//缓存字节数组File filesum;SearchFile(String fileName1, String searchName) throws IOException {//输入要查找的文件夹以及关键字this.fileName = fileName1;this.searchName = searchName;filesum = new File(fileName);list = new ArrayList();//用于存放包含关键字的文件的路径by = new byte[1024];if(filesum.exists()){//判断文件是否存在Search(filesum);if(list.size() != 0){for (Object lists : list) {//遍历数组输出存在相关字的文件路径System.out.println(lists.toString());}} else {System.out.println("文件都不含有关键字");}} else {System.out.println("输入的文件不存在!");}}public void Search(File file) throws IOException {String filename2 = null;if (file.isDirectory()) {//首先判断传入的文件是文件夹还是具体文件String[] s = file.list();File[] filelist = file.listFiles();for (File f : filelist) {Search(f);//使用递归遍历文件夹下所有文件}} else {FileInputStream fis = new FileInputStream(file);InputStreamReader read = new InputStreamReader(fis, "gbk");BufferedReader bfr = new BufferedReader(read);filename2 = file.getAbsolutePath();String line = null;int a = 0;while ((line = bfr.readLine()) != null) {if ((line.indexOf(searchName)) != -1) {//每次读取一行进行关键字的查找list.add(filename2);//若文件中包含关键字则将文件的路径添加到Ayyarlist中break;//如果此文件包含关键字,则不需要再继续检索此文件}}bfr.close();}}}


0 0