📄 nodeoperator.java
字号:
/*
* NodeOperator.java
*
* Created on 2006年11月18日, 下午7:52
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package btree;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.util.Stack;
/**
* 用来进行btree磁盘辅助操作的类
* @author Andy
*/
public class NodeOperator {
private RandomAccessFile idxFile;
private Stack<Long> gapStack;
/**
* 通过索引文件名创建一个操作类,如果不存在文件,创建一个,如果存在,将对这个文件进行读写
* @param fileName 索引文件名
* @return 一个FileOperator的实例
*/
public NodeOperator(String fileName) throws IOException {
//读取索引数据文件
try {
idxFile=new RandomAccessFile(fileName,"rw");
} catch (FileNotFoundException ex) {
//永远不会到达这里
}
try {
//读取空档文件
FileInputStream fis=new FileInputStream("idx.gap");
ObjectInputStream ois=new ObjectInputStream(fis);
gapStack=(Stack<Long>)ois.readObject();
ois.close();
fis.close();
} catch (FileNotFoundException ex) {
//没有空档文件,重新建立一个
gapStack=new Stack<Long>();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
/**
* 将一个btree的节点写入索引文件
* @param node 要写入的节点
*/
public void writeNode(Node node) throws IOException {
idxFile.seek(node.pointer);
idxFile.write(node.serialize());
}
/**
* 将一个节点从索引文件中读取出来
* @param pos 节点所在的文件位置
* @return 读取的节点
*/
public Node loadNode(long pos) throws IOException {
idxFile.seek(pos);
byte []b=new byte[Node.size()];
idxFile.read(b);
return Node.deserialize(b);
}
/**
* 删除一个节点
* @param node 要删除的节点
*/
public void deleteNode(Node node) {
gapStack.push(node.pointer);
}
/**
* 返回文件中下一个可用的节点位置
* @return 返回的节点位置
*/
public long getAvailableFilePointer() throws IOException {
if(gapStack.size()!=0)
return gapStack.pop();
else
return (long)idxFile.length();
}
/**
* 关闭索引文件,同时存储空档栈
*/
public void close() throws IOException {
//序列化空档栈
FileOutputStream fos=new FileOutputStream("idx.gap");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(gapStack);
oos.close();
fos.close();
//关闭文件
idxFile.close();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -