≪ログの検索|Search Log|ldap≫:フォルダの下にあるすべてのファイルに指定した文字列が含まれているかどうかを再帰的に遍歴します.

2093 ワード

シーン:
大量のログ・ファイルから、文字列を含むログ・ファイルを調べる必要があります.
public class TestDemo {

    public static void main(String[] args) throws Exception {
        //     
        String path = "E:\\backuplog1111\\wecruit_app\\backuplog";
        //      
        String content = "5d156b459b0d7889b8422cca";
        list(path,content);
    }


    public static void list(String sourcePath,String content) throws Exception {
        File file = new File(sourcePath);
        //                  
        List list = filesDirs(file, new ArrayList<>());
        //                
        for(String path:list){
            checkContainsString(path,content);
        }
    }



    /***
     *                  
     * @param file   
     * @param pathList          
     * @return           
     * @throws Exception
     */
    public static List filesDirs(File file, List pathList) throws Exception {
        if(file != null){
            if(file.isDirectory()){
                File[] files = file.listFiles();
                for(File f:files) {
                    filesDirs(f,pathList);
                }
            }else{
                pathList.add(file.toString());
            }
        }
        return pathList;
    }


    /**
     *              
     * @param path      
     * @param content      
     * @return     true,    false
     * @throws IOException
     */
    public static Boolean checkContainsString(String path,String content) throws IOException {
        File file = new File(path);
        InputStreamReader read = new InputStreamReader(new FileInputStream(file),"UTF-8");//       
        BufferedReader bufferedReader = new BufferedReader(read);
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {

            //        
            if (line.contains(content)) {
                System.out.println(line);
                System.out.println(path);
                return true;
            }
        }
        return false;
    }
}