sprinboot打包jar后读取不到/resource/data/ip2region.xdb的文件.
解决1:文件复制到项目外,直接用路径访问.
解决2: 如果文件必须再项目里,打包要包含,可以用代码从jar包里复制到服务器上.
1:maven打包要添加你的文件
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.xml</include>
<include>*.txt</include>
<include>*.properties</include>
<include>*.yml</include>
<include>mapper/*.xml</include>
<include>static/**</include>
<include>data/ip2region.xdb</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
2:打包后,文件jar包里,不在你的目录里.可以从jar包了复制过去.
//项目打包成jar包所在的根路径
String rootPath = applicationHome.getSource().getParentFile().toString();
String configFilePath = rootPath + "/data/ip2region.xdb";
File configFile = new File(configFilePath);
if (!configFile.exists()) {
try {
//获取类路径下的指定文件流 (项目目录下的: /resource/data/ip2region.xdb)
InputStream in = this.getClass().getClassLoader().getResourceAsStream("data/ip2region.xdb");
FileUtils.copyInputStreamToFile(Objects.requireNonNull(in, "/data/ip2region.xdb文件找不到"), configFile);
} catch (IOException e) {
//throw new IllegalArgumentException("保存文件证书失败->" + e.getMessage());
log.info("保存文件数据文件ip2region失败({}): {}", ip, e);
}
}
log.info("数据文件ip2region.xdb地址:{}", configFilePath);
网友评论