2013-03-20 21 views
0

我想寫一個函數,它需要一個關鍵字並搜索一個文件列表,然後打印出包含關鍵字的任何文件。Java:如何搜索關鍵字的文件?

到目前爲止,我所擁有的只是一個文件列表和關鍵字。

File[] files = new File("<directory>").listFiles(); 
Scanner keyword = new Scanner("hello"); 

我想現在我需要構建某種形式的循環,通過文件尋找關鍵字。任何幫助,即使是一個簡單的跟隨教程表示讚賞。

編輯:

的文件是文本文件,如果你想使用的掃描儀類,僅由一條線

+0

這裏是讀取文件的一個簡潔的例子:http://stackoverflow.com/a/3806154/16959 – 2013-03-20 18:19:44

+0

當然,如果你想閱讀文件的文本內容,看看在http: //tika.apache.org/,它是一個可以從Word文檔,網頁(避免使用HTML標籤),PDF等文檔中提取文本的庫。 – 2013-03-20 18:21:05

+1

儘管Java中可以這樣做,但是您是否考慮過你的要求)使用其中一個標準的命令行工具來做到這一點?例如,UNIX grep實用程序完全符合您的需求。 – codebox 2013-03-20 18:21:34

回答

3
File dir = new File("directory"); // directory = target directory. 
if(dir.exists()) // Directory exists then proceed. 
{ 
    Pattern p = Pattern.compile("keyword"); // keyword = keyword to search in files. 
    ArrayList<String> list = new ArrayList<String>(); // list of files. 

    for(File f : dir.listFiles()) 
    { 
    if(!f.isFile()) continue; 
    try 
    { 
     FileInputStream fis = new FileInputStream(f); 
     byte[] data = new byte[fis.available()]; 
     fis.read(data); 
     String text = new String(data); 
     Matcher m = p.matcher(text); 
     if(m.find()) 
     { 
     list.add(f.getName()); // add file to found-keyword list. 
     } 
     fis.close(); 
    } 
    catch(Exception e) 
    { 
     System.out.print("\n\t Error processing file : "+f.getName()); 
    } 

    } 
    System.out.print("\n\t List : "+list); // list of files containing keyword. 
} // IF directory exists then only process. 
else 
{ 
    System.out.print("\n Directory doesn't exist."); 
} 
+0

可以讓它清晰嗎?格式和東西 – user2148423 2013-03-20 18:27:47

+0

@jsn字節在搜索關鍵字之前轉換爲字符串。所以這不是問題。 – VishalDevgire 2013-03-20 18:32:14

+0

我需要下載模式嗎? – user2148423 2013-03-20 18:45:46

0

,這裏是你如何掃描文件針對特定的關鍵字: 掃描儀不過是一個遍歷提供給它的輸入的迭代器。

Scanner s = new Scanner(new File("abc.txt")); 
while(s.hasNextLine()){ 
    //read the file line by line 
String nextLine = s.nextLine(); 
      //check if the next line contains the key word 
    if(nextLine.contains("keyword")) 
    { 
       //whatever you want to do when the keyword is found in the file 
       and break after the first occurance is found 
      break; 
    } 
}