Read an Access database embedded in a JAR file

陌路散爱 提交于 2019-12-12 03:55:22

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/35590077/read-an-access-database-embedded-in-a-jar-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!