利用Java实现文件中的关键字查询

  1 package com.sinsoft.fileSearch;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileFilter;
  6 import java.io.FileNotFoundException;
  7 import java.io.FileOutputStream;
  8 import java.io.FileReader;
  9 import java.io.IOException;
 10 import java.io.PrintStream;
 11 import java.util.ArrayList;
 12 import java.util.Date;
 13 import java.util.List;
 14 import java.util.Scanner;
 15 
 16 /**
 17  * @Created by wxk
 18  * @User: wxk
 19  * @Date: 2015-12-4
 20  * @Time: 下午3:43:26
 21  */
 22 public class TextSearchFile2 {
 23 
 24     static int countFiles = 0;// 声明统计文件个数的变量
 25     static int countFolders = 0;// 声明统计文件夹的变量
 26     static int count = 0;
 27 
 28     static StringBuffer sb = new StringBuffer();
 29 
 30     public static File[] searchFile(File folder, final String keyWord) {// 递归查找包含关键字的文件
 31 
 32         File[] subFolders = folder.listFiles(new FileFilter() {// 运用内部匿名类获得文件
 33                     @Override
 34                     public boolean accept(File pathname) {// 实现FileFilter类的accept方法
 35                         if (pathname.isFile())// 如果是文件
 36                             countFiles++;
 37                         else
 38                             // 如果是目录
 39                             countFolders++;
 40                         if (pathname.isFile())
 41                             readFileByLines(pathname, keyWord);
 42                         return true;
 43 
 44                     }
 45                 });
 46 
 47         List<File> result = new ArrayList<File>();// 声明一个集合
 48         for (int i = 0; i < subFolders.length; i++) {
 49             // 循环显示文件夹或文件
 50             if (subFolders[i].isFile()) {
 51                 // 如果是文件则将文件添加到结果列表中
 52                 result.add(subFolders[i]);
 53             } else {
 54                 // 如果是文件夹,则递归调用本方法,然后把所有的文件加到结果列表中
 55                 File[] foldResult = searchFile(subFolders[i], keyWord);
 56                 for (int j = 0; j < foldResult.length; j++) {// 循环显示文件
 57                     result.add(foldResult[j]);// 文件保存到集合中
 58                 }
 59             }
 60         }
 61 
 62         File files[] = new File[result.size()];// 声明文件数组,长度为集合的长度
 63         result.toArray(files);// 集合数组化
 64         return files;
 65     }
 66 
 67     /**
 68      * 以行为单位读取文件的内容
 69      * 
 70      * @param fileName
 71      */
 72     public static Boolean readFileByLines(File file, String keyWord) {
 73         BufferedReader reader = null;
 74         try {
 75             // System.out.println("以行为单位读取文件内容,一次读一整行:");
 76             reader = new BufferedReader(new FileReader(file));
 77             String tempString = null;
 78             int line = 1;
 79             // 一次读入一行,直到读入null为文件结束
 80             while ((tempString = reader.readLine()) != null) {
 81                 // 显示行号
 82                 if (tempString.toLowerCase().contains(keyWord.toLowerCase())) {
 83                     sb.append("文件:" + file.getAbsolutePath() + "" + line
 84                             + "行: ——>" + tempString + "包含此关键字!");
 85                     sb.append("
");
 86                     count++;
 87                 }
 88                 line++;
 89             }
 90             reader.close();
 91         } catch (IOException e) {
 92             e.printStackTrace();
 93         } finally {
 94             if (reader != null) {
 95                 try {
 96                     reader.close();
 97                 } catch (IOException e1) {
 98                 }
 99             }
100         }
101         if (count > 0) {
102             return true;
103         }
104         return false;
105     }
106 
107     // 在文件里写入字符串
108     public static void WriteStringToFile(StringBuffer sb) {
109         Date date = new Date();
110         long time = date.getTime();
111         String fileString = "D:/log" + time + ".txt";
112         try {
113             File file = new File(fileString);
114             if (!file.exists()) {
115                 try {
116                     file.createNewFile();
117                     System.out.println("创建成功!");
118                 } catch (IOException e) {
119                     e.printStackTrace();
120                     System.out.println("创建失败!");
121                 }
122             }
123             PrintStream ps = new PrintStream(new FileOutputStream(file));
124             // ps.println(sb);// 往文件里写入字符串
125             ps.append(sb);//追加
126         } catch (FileNotFoundException e) {
127             e.printStackTrace();
128         }
129     }
130 
131     public static void main(String[] args) {// java程序的主入口处
132         String fileName = "";
133         String keyword = "";
134         Scanner sc = new Scanner(System.in);
135         System.out.print("请输入要搜索文件夹的路径:");
136         fileName = sc.next();
137         System.out.print("请输入要搜索的关键字:");
138         keyword = sc.next();
139 
140         if ("".equals(fileName) || "".equals(keyword)) {
141             System.out.println("路径或者关键字不能为空!");
142             System.exit(0);
143         }
144         
145         File folder = new File(fileName);// 默认目录
146 
147         if (!folder.exists()) {// 如果文件夹不存在
148             sb.append("目录不存在:" + folder.getAbsolutePath());
149             sb.append("
");
150             return;
151         }
152         File[] result = searchFile(folder, keyword);// 调用方法获得文件数组
153         sb.append("" + folder + " 以及所有子文件时查找对象" + keyword);
154         sb.append("
");
155         System.out.println("" + folder + " 以及所有子文件时查找对象" + keyword);
156         for (int i = 0; i < result.length; i++) {// 循环显示文件
157             File file = result[i];
158             sb.append(file.getAbsolutePath() + " ");
159             sb.append("
");
160         }
161         sb.append("查找了" + countFolders + " 个文件夹,共找到 " + +countFiles + " 个文件,"
162                 + count + " 个符合条件的内容");
163         sb.append("
");
164         System.out.println(sb);
165         WriteStringToFile(sb);
166     }
167 }

原文地址:https://www.cnblogs.com/wuxiaokai/p/5026310.html