Java 在本地文件中查找固定字符串
适用范围:只适用于在文本文档中查找(如,txt、java、c等等,并不适用与doc、xls等等这些文件),可嵌套文件夹。但是对中文不支持。
例如:文件夹:F:/demo
子文件夹:F:/demo/ert
查找结果:
最后附上全部代码:
1 package com.stafen.main; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.ArrayList; 6 import java.util.Collection; 7 import java.util.List; 8 9 import org.apache.commons.io.FileUtils; 10 import org.apache.commons.io.IOUtils; 11 12 public class Test { 13 /** 要查找的字符串 **/ 14 private static String strSearch = "QCNEA"; 15 /** 要查找的目录名称 **/ 16 private static String strPath = "E:/Project"; 17 18 @SuppressWarnings("unchecked") 19 public static void main(String[] args) { 20 21 File searchDir = new File(strPath); 22 List<Search> list = new ArrayList<Search>(); 23 try { 24 Collection<File> files = FileUtils.listFiles(searchDir, null, true); 25 List<String> lines = null; 26 for (File file : files) { 27 try { 28 lines = FileUtils.readLines(file, "UTF-8"); 29 } catch (IOException e) { 30 e.printStackTrace(); 31 } 32 for (int i = 0; i < lines.size(); i++) { 33 if (lines.get(i).indexOf(strSearch) != -1) { 34 Search s = new Search(); 35 s.setFilename(file.getPath()); 36 s.setLine(i + 1); 37 s.setContent(lines.get(i)); 38 list.add(s); 39 } 40 } 41 } 42 StringBuffer sb = new StringBuffer(); 43 if(list.size() == 0) { 44 System.out.println("【没有查到该字符串!】"); 45 return ; 46 } 47 for (Search s : list) { 48 sb.append("文件路径:" + s.getFilename() + "\n行数:" + s.getLine() + " \n所在行内容:" + s.getContent()).append(IOUtils.LINE_SEPARATOR); 49 sb.append("---------------------------------------------------------------------\n"); 50 } 51 System.out.println(sb.toString()); 52 } catch (Exception e) { 53 System.out.println("【没有找到该目录!】"); 54 } 55 } 56 57 }
Search.java文件
public class Search { private String filename; private int line; private String content; public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public void setLine(int line) { this.line = line; } public int getLine() { return line; } }