Haider
Haider

Reputation: 615

Error in creating a copy of mdb in memory

I am using below code to creating a copy of mdb file in memory but its giving null pointer exception on DatabaseBuilder constructor that no file exist, what i want is to create a copy of this manipulate it and return the copy to outputstream.

File tmp = new File("test.mdb");

FileChannel channel = MemFileChannel.newChannel(tmp,DatabaseImpl.RW_CHANNEL_MODE);

FileUtils.copyFile(file , tmp);

Database db = new DatabaseBuilder(tmp).setChannel(channel).open();

Upvotes: 1

Views: 188

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123819

So you have a pre-made Access database file as a resource in your project. You can open an in-memory copy of that database with Jackcess by first using Class#getResourceAsStream to open the resource ...

final String dbResourcePath = "/embedded.accdb";
@SuppressWarnings("rawtypes")
Class thisClass = JackcessTestMain.class;  // my "main" class
InputStream dbResourceStream = null;
// for running from executable jar 
dbResourceStream = thisClass.getResourceAsStream("/resources" + dbResourcePath);
if (dbResourceStream == null) {
    // for running inside the Eclipse IDE
    dbResourceStream = thisClass.getResourceAsStream(dbResourcePath);
}

... pass that InputStream to a Jackcess MemFileChannel ...

MemFileChannel mfc = MemFileChannel.newChannel(dbResourceStream);

... and then use DatabaseBuilder to open the Database from the channel:

Database db = new DatabaseBuilder().setChannel(mfc).open()

When finished making changes to the in-memory copy of the database you can send the contents of the channel to an OutputStream. For example,

db.close();
FileOutputStream fos = new FileOutputStream("C:/Users/Public/zzz.accdb");
mfc.transferTo(fos);
fos.close();

Upvotes: 2

Related Questions