使用tuple binding 来绑定自定义数据的步骤
1、 实例化你要存储的对象
2、 通过com.sleepycat.bind.tuple.TupleBinding class来创建一个tuple binding。
3、 创建一个database,跟序列化的对象不同,你只需要创建一个。
4、 通过继承第二步的类来创建一个entry binding 对象。
5、 存储和使用数据
自定义对象:
public class Student {
private int id;
private String name;
private int age;
//get()和set()方法
........
}
创建Tuple binding对象:
public class StudentTupleBinging extends TupleBinding{
@Override
public Object entryToObject(TupleInput input) {
int id=input.readInt();
String name=input.readString();
int age=input.readInt();
Student student=new Student();
student.setId(id);
student.setName(name);
student.setAge(age);
return student;
}
@Override
public void objectToEntry(Object object, TupleOutput output) {
Student student=(Student)object;
output.writeInt(student.getId());
output.writeString(student.getName());
output.writeInt(student.getAge());
}
}
存储:
public class StudentMainTwo {
private Environment myenv;
private Database mydb;
private TupleBinding studentBinding;
//d://workspace//MyTest//src//test//student.txt中的文件内容为
/**
* 1#Ashley#21
*2#bill#20
*3#skey#19
*4#Jessica#21
*5#Amanda#22
*6#Sarah#20
*7#Brittany#18
*
*/
private static File studentFile = new File("D://workspace//MyTest//src//test//student.txt");
private static DatabaseEntry theKey = new DatabaseEntry();
private static DatabaseEntry theData = new DatabaseEntry();
public static void main(String[] args) {
StudentMainTwo studentMainTwo=new StudentMainTwo();
studentMainTwo.start("D://bdb", 100000, "student");
try {
studentMainTwo.loadData();
studentMainTwo.showStudent();
} catch (Exception e) {
e.printStackTrace();
}
}
public void showStudent() throws DatabaseException {
Cursor cursor = mydb.openCursor(null, null);
try {
while (cursor.getNext(theKey, theData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
Student stu1 = (Student) studentBinding.entryToObject(theData);
System.out.println(stu1.getId() + " " + stu1.getName()
+ " " + stu1.getAge());
}
} catch (Exception e) {
System.err.println("Error on inventory cursor:");
System.err.println(e.toString());
e.printStackTrace();
} finally {
cursor.close();
}
}
public void loadData() throws DatabaseException {
List<String[]> students = loadFile(studentFile, 8);
studentBinding = new StudentTupleBinging();
//System.out.println(myenv.getConfig());
//Transaction txn = myenv.beginTransaction(null, null);
for (int i = 0; i < students.size(); i++) {
String[] student = students.get(i);
try {
theKey = new DatabaseEntry(student[0].getBytes("utf-8"));
Student stu = new Student();
stu.setId(Integer.parseInt(student[0]));
stu.setName(student[1]);
stu.setAge(Integer.parseInt(student[2]));
studentBinding.objectToEntry(stu, theData);
mydb.put(null, theKey, theData);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
public void start(String filename, long cacheSize, String dbname) {
EnvironmentConfig envconfig = new EnvironmentConfig();
envconfig.setAllowCreate(true);
envconfig.setReadOnly(false);
DatabaseConfig dbconfig = new DatabaseConfig();
dbconfig.setAllowCreate(true);
dbconfig.setReadOnly(false);
try {
myenv = new Environment(new File(filename), envconfig);
mydb = myenv.openDatabase(null, dbname, dbconfig);
} catch (Exception e) {
e.printStackTrace();
}
}
private List<String[]> loadFile(File theFile, int numFields) {
List<String[]> records = new ArrayList<String[]>();
try {
String theLine = null;
FileInputStream fis = new FileInputStream(theFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while ((theLine = br.readLine()) != null) {
String[] theLineArray = theLine.split("#");
if (theLineArray.length != numFields) {
System.out.println("Malformed line found in "
+ theFile.getPath());
System.out.println("Line was: '" + theLine);
System.out.println("length found was: "
+ theLineArray.length);
//System.exit(-1);
}
records.add(theLineArray);
}
// Close the input stream handle
fis.close();
} catch (FileNotFoundException e) {
System.err.println(theFile.getPath() + " does not exist.");
e.printStackTrace();
usage();
} catch (IOException e) {
System.err.println("IO Exception: " + e.toString());
e.printStackTrace();
System.exit(-1);
}
return records;
}
private static void usage() {
System.out.println("ExampleDatabasePut [-h <env directory>]");
System.out.println(" [-s <selections file>] [-v <vendors file>]");
System.exit(-1);
}
}