失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > SpringBoot项目打成jar包后 无法读取resources下的文件

SpringBoot项目打成jar包后 无法读取resources下的文件

时间:2023-08-08 05:22:22

相关推荐

SpringBoot项目打成jar包后 无法读取resources下的文件

最近在使用aspose将word转PDF并进行签章打印,读取凭证文件时遇到一个问题,凭证文件放在resources目录下,Windows下可正常读取,但是打成jar包部署到Linux服务器上却取不到文件。由此问题引出以下思考:

在本地项目读取文件时

this.getClass().getClassLoader().getResource("").getPath()+fileName

this.getClass().getResource("/filename").getPath()

都是可以成功的;

但是jar打包后上面方式读取文件时 会变成 jar!filename 这样的形式去读取文件,这样是读取不到文件的;

可以使用class.getResourceAsStream("/filename") 以流的形式读取文件,是可以读取的到的;

private static boolean getLicense() {boolean result = false;try {ClassLoader loader = Thread.currentThread().getContextClassLoader();// 凭证文件CONFIG_PATH =null;//method one(Windows能读到文件,Linux读不到文件)URL url = loader.getResource("config/license.xml");String filePath = url.getPath();logger.info("test-path : " + filePath);//test--path : file:/var/qianyue/java/test/qianyue-test.jar!/BOOT-INF/classes!/config/license.xmlFile file = new File(filePath);logger.info("test file : " + file.exists());//windows:true,linux:falseInputStream inputStream1 = CONFIG_PATH == null ? new FileInputStream(file) : new FileInputStream(new File(CONFIG_PATH));//method two(Windows能取到文件流,Linux也能取到文件流)InputStream flagInputStream = loader.getResourceAsStream("config/license.xml");logger.info("test file : " + flagInputStream.available());//windows:1609,linux:1609InputStream inputStream2 = CONFIG_PATH == null ? flagInputStream : new FileInputStream(new File(CONFIG_PATH));//method three(Windows能取到文件流,Linux也能取到文件流)InputStream indexInputStream = loader.getResource("config/license.xml").openStream();//原理与loader.getResourceAsStream一样logger.info("test file : " + indexInputStream.available());//windows:1609,linux:1609InputStream inputStream3 = CONFIG_PATH == null ? indexInputStream : new FileInputStream(new File(CONFIG_PATH));License aposeLic = new License();aposeLic.setLicense(inputStream3);result = true;} catch (Exception e) {e.printStackTrace();}return result;}

扩展:

class.getResource()不带"/“时候是从当前类所在包路径去获取资源

class.getResource()带”/"时候是从classpath的根路径获取

class.getResource()本质上也是调用了getClassLoader,只是封装了一层方便了我们使用而已

getClassLoader().getResource("")不带"/“时候是从classpath的根路径获取

getClassLoader().getResource(”/")路径中无法带有"/"

getResourceAsStream() 方法仅仅是获取对应路径文件的输入流,在路径的用法上与getResource()一致

如果觉得《SpringBoot项目打成jar包后 无法读取resources下的文件》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。