我正在尝试将类包的目录作为 .jar 中的 File
获取(层次结构为 /controller/core
):
File directory_file_of_package = new File(getClass().getResource("/controller/core").toURI());
当我在 IDE 中运行该程序时,它可以工作,但是当我将其作为独立的 .jar 运行时,它会给出以下错误:
java.lang.IllegalArgumentException: URI is not hierarchical
查看这些问题( why my URI is not hierarchical? 和 Java Jar file: use resource errors: URI is not hierarchical )对我没有帮助,因为这些问题涉及获取 .jar 中的 File
作为资源 (getResourceAsStream()
),但我想要获取的是一个目录。
此外,接受的答案指出:
Generally the IDEs separates on file system classes and resources. But when the jar is created they are put all together.
那么,有没有办法抓取到/controller/core
的目录呢?
我的 XY 问题:
我正在尝试使用 CSVJDBC ( http://csvjdbc.sourceforge.net/ ) 读取 .CSV 文件,并且 DriverManager
引用 CSV 文件的方式就像包含文件夹 是数据库,CSV 文件是表格。
public class SearchData {
void SearchData() {
try {
Class.forName("org.relique.jdbc.csv.CsvDriver");
File directory_file_of_package_containing_csv = new File(getClass().getResource("/controller/core").toURI());
// Driver points to directory which contains the CSV file as if it is the database
Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + directory_file_of_package_containing_csv.toString());
System.out.println("Connection established.");
Statement stmt = conn.createStatement();
System.out.println("Statement created.");
// CSV is named "data.csv" so the CsvDriver sees "data" as the table name
String sql = "SELECT id,name FROM data";
ResultSet results = stmt.executeQuery(sql);
...
} catch (ClassNotFoundException | SQLException | URISyntaxException e) {
e.printStackTrace();
}
}
}
如何将 CsvJdbc 指向 .jar 中包含的 csv 文件?
最佳答案
JAR 中根本没有包的目录。它可以在 IDE 中运行,因为您的类尚未打包在 JAR 文件中并驻留在某个目录中。但 JAR 的情况并非如此。
因此,如果您使用的某些库需要其中包含文件的目录,则通常无法使用类路径资源来实现此目的。其中一个选项是在临时目录中将资源创建为文件副本。
或者,您可能想研究 CsvJDBC documentation更接近:
To read data that is either held inside the Java application (for example, in a JAR file) or accessed remotely (for example, using HTTP requests), create a Java class that implements the interface
org.relique.io.TableReader
and give this class name in the connection URL. CsvJdbc then creates an instance of this class and calls thegetReader
method to obtain ajava.io.Reader
for each database table being read.
因此,您应该能够在没有临时目录的情况下解决 CsvJDBC 的问题。
关于java - 是否可以获取 .jar 中的类包的目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46394023/