[英]Java Maven Package Excel Files in Jar
我的资源文件夹中有一些资源文件(excel 文件),我想将它们打包到我的 jar 中,这样当我组装我的项目时,它会将 excel 文件打包到 jar 中,并且用户不必提供其他文件运行 jar 时。
我的项目结构是这样的:
/MyApp
|-src
|---main
|-----java
|-------app
|---------Main.java
|-----resources
|-------Something.xlsx
这是我的 maven pom:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>artifactId</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>sample.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
<resources>
<!-- regular resource processsing for everything except logback.xml -->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.*</include>
</includes>
</resource>
</resources>
</build>
</project>
这是我组装罐子的方法:
clean compile assembly:single
这会创建我的 jar,但是当我像java -jar myjar.jar
一样运行 jar 时,我收到以下错误:
java.io.FileNotFoundException: file:/Users/me/IdeaProjects/MyApp/target/myjar.jar!/Something.xlsx (No such file or directory)
显然,excel 文件没有被打包到 jar 中。 这是尝试打开资源文件的java代码:
URL file = getClass().getClassLoader().getResource("Something.xlsx");
有什么办法可以实现我想要的吗? 如果是/不是,在这种情况下最好的方法是什么?
我想到了。 我需要使用 InputStream 而不是 URL。 所以现在我的代码是这样的:
InputStream file = getClass().getResourceAsStream("/Something.xlsx");
这工作得很好。
我有类似的问题。 我在为根创建的“数据”文件夹下有 excel 测试数据文件。
2020-04-02 16:00:44 调试日志:46 - 读取 SMAPI UI 自动化 Excel 数据文件
Excel 文件路径:数据/SMAPI_UI_Automation.xlsx
Excel读取有问题:java.lang.NullPointerException
代码是: ExcelUtils.java
try {
String vXlsxFilePath = "data/" + fileName;
System.out.println("Excel file path"+vXlsxFilePath);
InputStream ExcelFile = ExcelUtils.class.getClass().getClassLoader().getResourceAsStream(vXlsxFilePath);
//FileInputStream ExcelFile = new FileInputStream(vXlsxFilePath);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
System.out.println("Excel Reading have problems"+e);
Log.error("Excel Reading have problems"+e);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.