Read an Access database embedded in a JAR file

2019-09-01 11:44发布

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条回答
相关推荐>>
2楼-- · 2019-09-01 12:00

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);
查看更多
登录 后发表回答