BulkAccessExample.java [plain text]
package db;
import com.sleepycat.db.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;
class BulkAccessExample {
private static final String FileName = "access.db";
public BulkAccessExample() {
}
public static void main(String[] argv) {
try {
BulkAccessExample app = new BulkAccessExample();
app.run();
} catch (DatabaseException dbe) {
System.err.println("BulkAccessExample: " + dbe.toString());
System.exit(1);
} catch (FileNotFoundException fnfe) {
System.err.println("BulkAccessExample: " + fnfe.toString());
System.exit(1);
}
System.exit(0);
}
public static String askForLine(InputStreamReader reader,
PrintStream out, String prompt) {
String result = "";
while (result != null && result.length() == 0) {
out.print(prompt);
out.flush();
result = getLine(reader);
}
return result;
}
public static String getLine(InputStreamReader reader) {
StringBuffer b = new StringBuffer();
int c;
try {
while ((c = reader.read()) != -1 && c != '\n') {
if (c != '\r')
b.append((char)c);
}
} catch (IOException ioe) {
c = -1;
}
if (c == -1 && b.length() == 0)
return null;
else
return b.toString();
}
public void run() throws DatabaseException, FileNotFoundException {
new File(FileName).delete();
DatabaseConfig config = new DatabaseConfig();
config.setErrorStream(System.err);
config.setErrorPrefix("BulkAccessExample");
config.setType(DatabaseType.BTREE);
config.setAllowCreate(true);
config.setMode(0644);
Database table = new Database(FileName, null, config);
InputStreamReader reader = new InputStreamReader(System.in);
for (;;) {
String line = askForLine(reader, System.out, "input> ");
if (line == null)
break;
String reversed = (new StringBuffer(line)).reverse().toString();
StringEntry key = new StringEntry(line);
StringEntry data = new StringEntry(reversed);
try {
if (table.putNoOverwrite(null, key, data) == OperationStatus.KEYEXIST)
System.out.println("Key " + line + " already exists.");
} catch (DatabaseException dbe) {
System.out.println(dbe.toString());
}
System.out.println("");
}
Cursor cursor = table.openCursor(null, null);
DatabaseEntry foo = new DatabaseEntry();
MultipleKeyDataEntry bulk_data = new MultipleKeyDataEntry();
bulk_data.setData(new byte[1024 * 1024]);
bulk_data.setUserBuffer(1024 * 1024, true);
while (cursor.getNext(foo, bulk_data, null) == OperationStatus.SUCCESS) {
StringEntry key, data;
key = new StringEntry();
data = new StringEntry();
while (bulk_data.next(key, data))
System.out.println(key.getString() + " : " + data.getString());
}
cursor.close();
table.close();
}
static class StringEntry extends DatabaseEntry {
StringEntry() {
}
StringEntry(String value) {
setString(value);
}
void setString(String value) {
byte[] data = value.getBytes();
setData(data);
setSize(data.length);
}
String getString() {
return new String(getData(), getOffset(), getSize());
}
}
}