2017-09-24 71 views
0

我試圖讓我的.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作爲資源內的FilegetResourceAsStream()) ,但我想獲得的是一個目錄。

此外,公認的答案狀態是:

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文件?

回答

1

簡而言之,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 the getReader method to obtain a java.io.Reader for each database table being read.

所以,你應該能夠解決這個問題的CsvJDBC沒有臨時目錄。

相關問題