javamaven在Jar中打包Excel文件
我的资源文件夹中有一些资源文件excel文件,我想将它们打包到我的jar中,这样当我组装我的项目时,它会将excel文件打包到jar中,并且用户在运行jar时不必提供额外的文件 我的项目结构如下:javamaven在Jar中打包Excel文件,java,excel,maven,intellij-idea,jar,Java,Excel,Maven,Intellij Idea,Jar,我的资源文件夹中有一些资源文件excel文件,我想将它们打包到我的jar中,这样当我组装我的项目时,它会将excel文件打包到jar中,并且用户在运行jar时不必提供额外的文件 我的项目结构如下: /MyApp |-src |---main |-----java |-------app |---------Main.java |-----resources |-------Something.xlsx InputStream file = getCla
/MyApp
|-src
|---main
|-----java
|-------app
|---------Main.java
|-----resources
|-------Something.xlsx
InputStream file = getClass().getResourceAsStream("/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>
这会创建我的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。现在我的代码是这样的:
/MyApp
|-src
|---main
|-----java
|-------app
|---------Main.java
|-----resources
|-------Something.xlsx
InputStream file = getClass().getResourceAsStream("/Something.xlsx");
这非常有效。我也有类似的问题。我在为根目录创建的数据文件夹下有excel测试数据文件 2020-04-02 16:00:44调试日志:46-读取SMAPI UI自动化Excel数据文件 Excel文件路径:data/SMAPI\u UI\u Automation.xlsx Excel读取有问题:java.lang.NullPointerException 代码是:ExcelUtils.java
@Rechard为什么不将resource dir放在src目录中?您是否尝试过用WinZip之类的东西打开您的jar,以确保excel文件确实打包在jar中?@gonzo看起来excel在jar中,但由于某种原因仍然找不到它。@Richard这是个好消息!这意味着POM是正确的。您可能只想玩一下打开相关资源文件的java代码。尝试参考资料/Something.xlsx..或只是/Something.xlsx。。。