[英]Include excel in executable .jar file
我必須從 excel 文件中讀取數據並在我的應用程序中顯示數據。 我想將我的 excel 文件(數據文件)與可執行 jar 一起打包。 我在主項目文件夾中創建了一個源文件夾,並將其命名為“ res
”。 在“ res
”中,我有 2 個子文件夾(普通文件夾),分別稱為“ images
”和“ data
”。 在數據文件夾中,我放置了 excel 文件。
我的項目結構
構建路徑
導出為 JAR
問題:
當我從 Eclipse 運行該應用程序時,它可以完美運行,但是當我將它導出為 jar 時,該應用程序不起作用。它能夠找到圖像但找不到 excel 文件。
換句話說,當我從 eclipse 內部運行應用程序時(右鍵單擊 -> 運行方式 -> Java 應用程序),它運行完美。 但是當啟動導出的 JAR 文件(“Tool.jar”)時,它無法讀取 excel 數據。
讀取Excel的代碼
URL excelResources = getClass().getResource("/excel/data.xls");
File excel = new File(excelResources.toURI());
FileInputStream fis = new FileInputStream(excel);
這個...
URL excelResources = getClass().getResource("/excel/data.xls");
File excel = new File(excelResources.toURI());
FileInputStream fis = new FileInputStream(excel);
不是嵌入式資源的工作方式。 您不能再像訪問文件系統上的文件一樣訪問 excel 文件,因為它不是,它嵌入在 Jar 文件中。
如果您需要 InputStream,請使用Class#getResourceAsStream
try (InputStream is = getClass().getResourceAsStream("/excel/data.xls")) {
//...
} catch (IOException exp) {
exp.printStackTrace();
}
使用 maven 可以通過插件來完成:
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>your.class.Name</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<resources>
<resource>
<directory>${basedir}/src/main/res/data</directory>
<filtering>false</filtering>
</resource>
</resources>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.