서브디렉토리 단어검색

 

WordSearch.java

 

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class WordSearch {

 

 public static void main(String[] args) {
  
  WordSearch wordSearch = new WordSearch();
  
  File rootDir = new File("C:\\특정폴더");
  wordSearch.recursiveDir(rootDir.listFiles());
 }
 
 // 재귀호출 당하는 디렉토리
 public File [] recursiveDir(File [] dirs) {
  
  String dirPath = "";
  for (int i=0 ; i<dirs.length ; i++) {
   if (dirs[i].isDirectory()) {

 

// 재귀호출 부분 (서브디렉토리가 존재하면 속으로 파고 들어가기)
    if (dirs.length > 0) {
     recursiveDir(dirs[i].listFiles());
    }

 

    dirPath = dirs[i].getAbsolutePath();
    if (dirPath.toLowerCase().indexOf("검색단어") > -1) {
     // System.out.println("뒤벼본 디렉토리 → " + dirPath);
    }
   }
   if (dirs[i].isFile()) {
    searchWord(dirs[i]);
   }
  }
  return null;
 }
 
 // 파일 알맹이 검색
 public void searchWord(File filePath) {
  
  BufferedReader reader = null;
  try {
   // 파일 열어 파일 알맹이 한 줄씩 읽기
   reader = new BufferedReader(new FileReader(filePath));
   while (true) {
    // 한 행 읽기
    String str = reader.readLine();
    if (str == null) break;
    // 읽은 행에 "검색어"가 있으면 데이터 출력
    if (str.toLowerCase().indexOf("tb_al001") > -1) {
     System.out.println("뒤빈 파일 → " + filePath.getAbsolutePath());
     System.out.println("검색 결과 → " + str);
     System.out.println("");
    }
   }
  } catch (FileNotFoundException fnfe) {
   System.out.println("파일이 존재하지 않습니다.");
  } catch (IOException ioe) {
   System.out.println("파일을 읽을 수 없습니다.");
  } finally {
   try {
    // 열었던 파일 닫음
    reader.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }
 
}

 

+ Recent posts