首先我们看看类FSDirectory的源代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import org.apache.lucene.index.IndexFileNameFilter;
// Used only for WRITE_LOCK_NAME in deprecated create=true case:
import org.apache.lucene.index.IndexWriter;
public class FSDirectory extends Directory {
//主要是用来缓存FilePath与FSDirectory,主要是保证针对统一目录,只能有一个FSDirectory实例
private static final Map DIRECTORIES = new HashMap();
//主要判断是否给目录上锁
private static boolean disableLocks = false;
//设置是否给目录上锁,一般只能用户只读目录。
//They should only be disabled if the index
// is on a read-only medium like a CD-ROM
public static void setDisableLocks(boolean doDisableLocks) {
FSDirectory.disableLocks = doDisableLocks;
}
//f返回是否给目录上锁
public static boolean getDisableLocks() {
return FSDirectory.disableLocks;
}
public static final String LOCK_DIR = System.getProperty("org.apache.lucene.lockDir",
System.getProperty("java.io.tmpdir"));
private static Class IMPL; //主要是获取FSDirectory的实例
static {
try {
String name =System.getProperty("org.apache.lucene.FSDirectory.class",
FSDirectory.class.getName());
IMPL = Class.forName(name); //首先获取该类的名称,然后在获取该类的Class实例
} catch (ClassNotFoundException e) {
throw new RuntimeException("cannot load FSDirectory class: " + e.toString(), e);
} catch (SecurityException se) {
try {
IMPL = Class.forName(FSDirectory.class.getName()); //直接使用JAVA反射获取该类Class实例
} catch (ClassNotFoundException e) {
throw new RuntimeException("cannot load default FSDirectory class: " + e.toString(), e);
}
}
}
private static MessageDigest DIGESTER; //获取加密
static {
try {
DIGESTER = MessageDigest.getInstance("MD5"); //使用MD5加密
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.toString(), e);
}
}
private byte[] buffer = null;
/**静态方法,根据基于指定目录,返回该目录中对应的一个FSDirectory实例 */
public static FSDirectory getDirectory(String path) throws IOException {
return getDirectory(new File(path), null);
}
/** 静态方法,根据指定的路径path以及锁工厂LockFactory参数,返回该路径的一个FSDirectiry实例 */
public static FSDirectory getDirectory(String path, LockFactory lockFactory) throws IOException {
return getDirectory(new File(path), lockFactory);
}
/**静态方法,根据指定的File对象,返回该路径的一个FSDirectiry实例 */
public static FSDirectory getDirectory(File file) throws IOException {
return getDirectory(file, null);
}
/**静态方法,根据指定File对象以及锁工厂LockFactory参数,返回该路径的一个FSDirectiry实例
其他方法,都最终转化为该方法来实现 */
public static FSDirectory getDirectory(File file, LockFactory lockFactory) throws IOException
{
file = new File(file.getCanonicalPath()); //定义一个File对象,以传递的参数作为目录
if (file.exists() && !file.isDirectory()) //首先判断文件存在时,是否是目录
throw new IOException(file + " not a directory");
if (!file.exists()) //如果文件不存在。则创建
if (!file.mkdirs()) throw new IOException("Cannot create directory: " + file