// 读取名称为name的文件,返回一个输出流,以便定义对读取出来的内容进行操作
public IndexInput openInput(String name) throws IOException {
return new FSIndexInput(new File(directory, name));
}
// 打开指定名称为name的文件,指定大小为缓冲区大小bufferSize,返回一个输入流
public IndexInput openInput(String name, int bufferSize) throws IOException {
return new FSIndexInput(new File(directory, name), bufferSize);
}
// 一个字符缓冲区,将字节转换为十六进制
private static final char[] HEX_DIGITS =
{\'0\',\'1\',\'2\',\'3\',\'4\',\'5\',\'6\',\'7\',\'8\',\'9\',\'a\',\'b\',\'c\',\'d\',\'e\',\'f\'};
// 获取锁的标识ID
public String getLockID() {
String dirName;
try {
dirName = directory.getCanonicalPath();
} catch (IOException e) {
throw new RuntimeException(e.toString(), e);
}
byte digest[];
synchronized (DIGESTER) {
digest = DIGESTER.digest(dirName.getBytes());
}
StringBuffer buf = new StringBuffer();
buf.append("lucene-");
for (int i = 0; i < digest.length; i++) {
int b = digest[i];
buf.append(HEX_DIGITS[(b >> 4) & 0xf]);
buf.append(HEX_DIGITS[b & 0xf]);
}
return buf.toString();
}
// 关闭目录
public synchronized void close() {
if (--refCount <= 0) {
synchronized (DIRECTORIES) {
DIRECTORIES.remove(directory);
}
}
}
public File getFile() {
return directory;
}
/** For debug output. */
public String toString() {
return this.getClass().getName() + "@" + directory;
}
// FSIndexInput是一个静态内部类,用于管理文件系统中的索引文件输入流
protected static class FSIndexInput extends BufferedIndexInput {
private static class Descriptor extends RandomAccessFile {
// 用于记录文件打开状态的boolean型变量isOpen
private boolean isOpen;
long position;
final long length;
public Descriptor(File file, String mode) throws IOException {
super(file, mode);
isOpen=true;
length=length();
}
public void close() throws IOException {
if (isOpen) {
isOpen=false;
super.close();
}
}
protected void finalize() throws Throwable {
try {
close();
} finally {
super.finalize();
}
}
}
private final Descriptor file;
boolean isClone;
public FSIndexInput(File path) throws IOException {
this(path, BufferedIndexInput.BUFFER_SIZE);
}
public FSIndexInput(File path, int bufferSize) throws IOException {
super(bufferSize);
file = new Descriptor(path, "r");
}
// 比较底层的读取操作,主要是对字节操作
protected void readInternal(byte[] b, int offset, int len)
throws IOException {
synchronized (file) {
long position = getFilePointer();
if (position != file.position) {
file.seek(position);
file.position = position;
}
int total = 0;
do {
int i = file.read(b, offset+total, len-total);
if (i == -1)
throw new IOException("read past EOF");
file.position += i;
total += i;
} while (total < len);
}
}
public void close() throws IOException {
if (!isClone) file.close();
}
protected void seekInternal(long position) {
}
public long length() {
return file.length;
}