1. 程式人生 > >java 查詢目錄下檔案內容包含某個字串的檔案

java 查詢目錄下檔案內容包含某個字串的檔案

這個java類主要是用來查詢檔案內容的,而不是查詢檔名的。主要作用是查詢目錄下所有檔案的檔案內容包含特定字串的檔案,並列印輸出位置和找到的字元數量。可以定義多個字元進行查詢,不需要擔心檔案格式問題,非常方便!

package com.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class SearchStrInPath  
{  
    public static int mount = 0;  
    public static void main(String[] args)   
    {  
        String filename = "e:\\20161215\\wsbsbb";
        //建立一個 File 例項,表示路徑名是指定路徑引數的檔案  
        File file = new File(filename);
        args=new String[]{"PW"};//
        for (int i = 0; i < args.length; i++) {
            findFile(file, args[i]);  
            print(args[i]);  
		}

    }  
    public static boolean isTrueFile(File file)   
    {  
        if(!file.exists() || !file.canRead())  
        return false;  
        if (file.getName().startsWith("."))  
        return false;  
        if (file.getName().endsWith("."))  
        return false;  
        return true;  
    }  
    public static void findFile(File file, String word)   
    {  
        File[] listFiles = file.listFiles();   
        //得到一個File陣列,它預設是按檔案最後修改日期排序的  
        for (int i = 0; i < listFiles.length; i++)   
        {  
           if (listFiles[i].isDirectory())  
           findFile(listFiles[i], word);  
           else if (isTrueFile(listFiles[i]))  
           search(listFiles[i], word);  
        }  
    }  
    public static void search(File file, String word)   
    {  
        try   
        {  
            int j = 0, k = 0, ch = 0;  
            String str = null;  
            FileReader in = new FileReader(file);  
            while ((ch = in.read()) != -1)   
            {  
                str += (char) ch;  
            }  
            if (str != null)  
            {  
                while (str.indexOf(word, j) != -1)   
                {  
                    k++;  
                    j = str.indexOf(word, j) + 1; // 返回第一次出現的指定子字串在此字串中的索引  
                }  
            }  
            if (k > 0)   
            {  
                System.out.println("在" + file.getAbsolutePath() + "有    " + k+ " 個關鍵字" + word);  
                mount++;  
            }  
            in.close();  
        }   
        catch (FileNotFoundException e)  
        {  
            e.printStackTrace();  
        }   
        catch (IOException e)  
        {  
            e.printStackTrace();  
        }  
    }  
    public static void print(String word)  
    {  
        if (mount != 0)   
        {  
            System.out.println("一共找到    " + mount + " 個檔案包含關鍵字" + word + "! \n");
            mount=0;
        }   
        else   
        {  
            System.out.println("沒有找到相應的檔案");  
        }  
    }  
}