读取嵌入在JAR文件中的Access数据库 [英] Read an Access database embedded in a JAR file
问题描述
我有一个使用UCanAccess读取Access数据库的Java程序.将程序导出到JAR文件时,无法读取JAR内部的数据库文件.
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.
我尝试过使用getClass().getResource("/Database.accdb").getPath()
,但是它不起作用.
I tried with getClass().getResource("/Database.accdb").getPath()
but it doesn't work.
我该如何解决?
推荐答案
您不能直接从可运行JAR文件中嵌入的副本中打开数据库文件. UCanAccess要求数据库文件是真实"文件,因此您需要从JAR中提取它,然后打开该副本.
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.
例如,要将数据库从JAR提取到一个临时文件中:
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);
这篇关于读取嵌入在JAR文件中的Access数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!