打包为Jar后无法读取resources目录下license_.cxl授权文件如何解决
问题根因
第三方库的setLicense方法仅支持读取本地磁盘上的物理文件路径,而打包为Jar后,license_.cxl是Jar包内部的压缩资源,不存在独立的磁盘文件路径,因此直接传入Jar内资源路径会读取失败。
可行解决方案
核心思路是程序启动时将Jar内的授权文件临时写入本地磁盘,再把临时文件的路径传给第三方库:
- 读取Jar内部的授权文件资源流
- 将资源流写入本地临时目录生成临时文件
- 传入临时文件的绝对路径给
setLicense方法 - 配置JVM退出时自动清理临时文件,避免冗余文件残留
代码示例
Spring项目可直接使用内置工具类:
import org.springframework.util.FileCopyUtils; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; // 调用第三方库方法前执行 InputStream licenseStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("license_.cxl"); if (licenseStream == null) { throw new RuntimeException("内置授权文件缺失"); } // 生成临时文件 File tempLicense = File.createTempFile("license_", ".cxl"); tempLicense.deleteOnExit(); // JVM退出自动删除临时文件 // 写入临时文件 FileCopyUtils.copy(licenseStream, new FileOutputStream(tempLicense)); // 传入临时文件路径 xxxThirdPartySdk.setLicense(tempLicense.getAbsolutePath());
非Spring项目使用原生IO实现:
import java.io.*; // 调用第三方库方法前执行 InputStream licenseStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("license_.cxl"); if (licenseStream == null) { throw new RuntimeException("内置授权文件缺失"); } File tempLicense = File.createTempFile("license_", ".cxl"); tempLicense.deleteOnExit(); try (OutputStream os = new FileOutputStream(tempLicense)) { byte[] buffer = new byte[1024]; int len; while ((len = licenseStream.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { licenseStream.close(); } xxxThirdPartySdk.setLicense(tempLicense.getAbsolutePath());
补充说明
- 不需要修改Gradle打包配置,只要确认Jar包内
BOOT-INF/classes下存在license_.cxl即可 - 若对安全要求较高,也可以在授权初始化完成后主动调用
tempLicense.delete()手动删除临时文件
内容的提问来源于stack exchange,提问作者stackUser
相关产品推荐
相关产品推荐

