0

I have a Java program which uses UCanAccess to read an Access database. When I export my program to a JAR file I can't read the database file that is inside the JAR.

I tried with getClass().getResource("/Database.accdb").getPath() but it doesn't work.

How can I fix it?

Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
Carlo
  • 36
  • 3
  • 2
    I'm not sure you can, directly, you might have to extract the database from the jar and store it on the disk somewhere, having it embedded like this means the database would read-only (assuming you could read it from within the jar) – MadProgrammer Feb 23 '16 at 23:14

1 Answers1

4

You cannot open the database file directly from the copy imbedded in the runnable JAR file. UCanAccess requires that the database file be a "real" file, so you'll need to extract it from the JAR and then open that copy.

For example, to extract the database from the JAR into a temporary file:

java.io.File dbFile = java.io.File.createTempFile("tempdb", ".accdb");
dbFile.deleteOnExit();
java.nio.file.Files.copy(
        YourClassName.class.getResourceAsStream("/stuff.accdb"), 
        dbFile.toPath(), 
        java.nio.file.StandardCopyOption.REPLACE_EXISTING);
String connStr = String.format(
        "jdbc:ucanaccess://%s;immediatelyReleaseResources=true", 
        dbFile.getAbsolutePath());
Connection conn = DriverManager.getConnection(connStr);
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418