2017-09-24 73 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没有临时目录。

相关问题