1 17 18 19 20 package org.apache.lenya.search; 21 22 import java.io.File ; 23 import java.io.FileInputStream ; 24 import java.io.IOException ; 25 import java.nio.CharBuffer ; 26 import java.nio.MappedByteBuffer ; 27 import java.nio.channels.FileChannel ; 28 import java.nio.charset.Charset ; 29 import java.nio.charset.CharsetDecoder ; 30 import java.util.ArrayList ; 31 import java.util.List ; 32 import java.util.regex.Matcher ; 33 import java.util.regex.Pattern ; 34 35 38 public class Grep { 39 40 private static Charset charset = Charset.forName("ISO-8859-15"); 42 private static CharsetDecoder decoder = charset.newDecoder(); 43 44 54 public static boolean containsPattern(File file, Pattern pattern) 55 throws IOException { 56 57 FileInputStream fis = new FileInputStream (file); 59 FileChannel fc = fis.getChannel(); 60 61 int sz = (int)fc.size(); 63 MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); 64 65 CharBuffer cb = decoder.decode(bb); 67 68 Matcher pm = pattern.matcher(cb); 71 boolean result = pm.find(); 72 73 fc.close(); 75 fis.close(); 76 77 return result; 78 } 79 80 93 public static String [] findPattern(File file, Pattern pattern, int group) 94 throws IOException { 95 96 ArrayList occurences = new ArrayList (); 97 98 FileInputStream fis = new FileInputStream (file); 100 FileChannel fc = fis.getChannel(); 101 102 int sz = (int)fc.size(); 104 MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); 105 106 CharBuffer cb = decoder.decode(bb); 108 109 Matcher pm = pattern.matcher(cb); 112 while (pm.find()) { 113 occurences.add(pm.group(group)); 114 } 115 116 fc.close(); 118 fis.close(); 119 120 return (String [])occurences.toArray(new String [occurences.size()]); 121 122 } 123 124 134 private static List find_internal(File file, Pattern pattern) 135 throws IOException { 136 ArrayList fileList = new ArrayList (); 137 138 if (file.isDirectory()) { 139 String [] children = file.list(); 140 for (int i = 0; i < children.length; i++) { 141 fileList.addAll( 142 find_internal( 143 new File (file.getAbsolutePath(), children[i]), 144 pattern)); 145 } 146 } else if (file.isFile() && containsPattern(file, pattern)) { 147 fileList.add(file); 148 } 149 return fileList; 150 } 151 152 162 public static File [] find(File file, String searchString) 163 throws IOException { 164 Pattern pattern = Pattern.compile(searchString); 165 List fileList = find_internal(file, pattern); 166 return (File [])fileList.toArray(new File [fileList.size()]); 167 } 168 } 169 | Popular Tags |