KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lucene > demo > IndexFiles


1 package org.apache.lucene.demo;
2
3 /**
4  * Copyright 2004 The Apache Software Foundation
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 import org.apache.lucene.analysis.standard.StandardAnalyzer;
20 import org.apache.lucene.index.IndexWriter;
21
22 import java.io.File JavaDoc;
23 import java.io.FileNotFoundException JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.util.Date JavaDoc;
26
27 class IndexFiles {
28   public static void main(String JavaDoc[] args) throws IOException JavaDoc {
29     String JavaDoc usage = "java " + IndexFiles.class + " <root_directory>";
30     if (args.length == 0) {
31       System.err.println("Usage: " + usage);
32       System.exit(1);
33     }
34
35     Date JavaDoc start = new Date JavaDoc();
36     try {
37       IndexWriter writer = new IndexWriter("index", new StandardAnalyzer(), true);
38       indexDocs(writer, new File JavaDoc(args[0]));
39
40       writer.optimize();
41       writer.close();
42
43       Date JavaDoc end = new Date JavaDoc();
44
45       System.out.print(end.getTime() - start.getTime());
46       System.out.println(" total milliseconds");
47
48     } catch (IOException JavaDoc e) {
49       System.out.println(" caught a " + e.getClass() +
50        "\n with message: " + e.getMessage());
51     }
52   }
53
54   public static void indexDocs(IndexWriter writer, File JavaDoc file)
55     throws IOException JavaDoc {
56     // do not try to index files that cannot be read
57
if (file.canRead()) {
58       if (file.isDirectory()) {
59         String JavaDoc[] files = file.list();
60         // an IO error could occur
61
if (files != null) {
62           for (int i = 0; i < files.length; i++) {
63             indexDocs(writer, new File JavaDoc(file, files[i]));
64           }
65         }
66       } else {
67         System.out.println("adding " + file);
68         try {
69           writer.addDocument(FileDocument.Document(file));
70         }
71         // at least on windows, some temporary files raise this exception with an "access denied" message
72
// checking if the file can be read doesn't help
73
catch (FileNotFoundException JavaDoc fnfe) {
74           ;
75         }
76       }
77     }
78   }
79 }
80
Popular Tags