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?
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);