MDB to CSV conversion in Java using Jackcess

1. Download jackcess from here

2. Write this code in your Utility Package:

import com.healthmarketscience.jackcess.Column;
import com.healthmarketscience.jackcess.Cursor;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Index;
import com.healthmarketscience.jackcess.Table;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

void dumpDatabase(Database mdb, BufferedWriter out,
String sourceFilePathWithName, String destinationFilePathWithName) throws Exception {
Database db = null;
BufferedWriter out = null;
try {
db = Database.open(new File(sourceFilePathWithName));
FileWriter fstream = new FileWriter(destinationFilePathWithName);
out = new BufferedWriter(fstream);

Iterator tableNamesIterator = db.getTableNames().iterator();
if (tableNamesIterator.hasNext()) {
Table table = db.getTable(tableNamesIterator.next().toString());
dumpTable(table, out);
}
} catch (IOException ex) {

} finally {
try {
db.close();
//Close the output stream
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

void dumpTable(Table table, BufferedWriter out) throws Exception {
boolean inside = false;
for (Index index : table.getIndexes()) {
index.initialize();
}
for (Column col : table.getColumns()) {
if (inside) {
out.write(“,”);
} else {
inside = true;
}
out.write(col.getName());
}
out.write(“\n”);
for (Map<String, Object> row : Cursor.createCursor(table)) {
inside = false;
for (Map.Entry<String, Object> entry : row.entrySet()) {
Object v = entry.getValue();
if (inside) {
out.write(“,”);
} else {
inside = true;
}
out.write(v.toString());
}
out.write(“\n”);
}
}

3. Call the method dumpDatabase and pass it the parameters required.

Tags: ,

No comments yet.

Leave a Reply