我試圖讓我的.jar內的類包的目錄爲File
(層次是/controller/core
):是否可以在.jar中獲取類包的目錄?
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文件?