Lucene学习笔记--创建索引(Create Index)

public void createIndex() {
		try {
			File file = new File(FILE_PATH);	//FILE_PATH为所要创建索引的文件的绝对地址,在地址完全可以用String来代替
			Document doc = new Document();
			IndexWriter indexWriter = new IndexWriter(INDEX_STORE_PATH,analyzer, true,MaxFieldLength.LIMITED);
			//INDEX_STORE_PATH索引存放的地址
			
			Field field =new Field("content",loadFileToString(file),Field.Store.NO, Field.Index.TOKENIZED);
			doc.add(field);
			
			field=new Field("name",file.getName(),Field.Store.YES, Field.Index.TOKENIZED);
			doc.add(field);
			
			field=new Field("path",file.getPath(),Field.Store.YES, Field.Index.TOKENIZED);
			doc.add(field);
			
			indexWriter.addDocument(doc);
			
			indexWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
public String loadFileToString(File file) {
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			StringBuffer sb = new StringBuffer();
			String line = br.readLine();
			while (line != null) {
				sb.append(line);
				line = br.readLine();
			}
			br.close();
			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

相关推荐