private static final File INDEX_PATH = new File(".\\index");// 索引文件位置 private static final Analyzer ANALYZER = new WhitespaceAnalyzer(Version.LUCENE_35); //Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35); //Analyzer analyzer = new WhitespaceAnalyzer(Version.LUCENE_35);
static boolean buildIndex() { File readFile = new File(".\\duomicibiao.txt"); HashMap<String, String> words = readFile(readFile);
Document doc; if (words != null) { try { IndexWriterConfig writerConfig = new IndexWriterConfig(Version.LUCENE_35, ANALYZER); IndexWriter writer = new IndexWriter(FSDirectory.open(INDEX_PATH), writerConfig);
Set<String> keys = words.keySet();
for (Iterator<String> it = keys.iterator(); it.hasNext();) { String key = it.next(); doc = new Document(); Field index = new Field("index", key, Field.Store.YES,Field.Index.ANALYZED); Field contents = new Field("contents", words.get(key),Field.Store.YES, Field.Index.NO); doc.add(index); doc.add(contents); writer.addDocument(doc); } writer.close();// 这里不关闭建立索引会失败 return true; } catch (Exception e) { e.printStackTrace(); return false; } } else { System.out.println("文件读取错误"); return false; }