springboot应用在linux环境获取resource目录下文件报错

文章讨论了SpringBoot应用在不同操作系统中获取resource目录下文件路径的差异,指出在Linux环境下Hutool获取的路径不正确。解决办法是通过ClassLoader获取资源流,因为直接通过FileInputStream在jar包内无法读取文件。
摘要由CSDN通过智能技术生成

一现象:

        springboot应用在window环境中获取resource目录下文件路径正常,linux环境中获取resource目录下文件路径异常。

二代码:

        FileUtil.getAbsolutePath("templates/xx模板.xlsx");  使用的是hutool提供的获取绝对路径的类,

windows获取的路径:

{"msg":"D:/ttttttttttttttt/aerosoft/aerosoft/safe/target/classes/templates/xx.docx","code":200}

linux获取的路径: 

{"msg":"/usr/local/aerosofe/aerosoft-safe/aerosoft-safe.jar!/BOOT-INF/classes!/templates/%e3%80%90%e5%b2%97%e4%bd%8d%e6%96%87%e4%bb%b6%e3%80%91%e5%ae%89%e5%85%a8%e6%89%bf%e8%af%ba%e4%b9%a6%e6%a8%a1%e6%9d%bf.docx","code":200} 显然这不是一个正确的路径

hutool代码如下

	/**
	 * 获取绝对路径<br>
	 * 此方法不会判定给定路径是否有效(文件或目录存在)
	 *
	 * @param path      相对路径
	 * @param baseClass 相对路径所相对的类
	 * @return 绝对路径
	 */
	public static String getAbsolutePath(String path, Class<?> baseClass) {
		String normalPath;
		if (path == null) {
			normalPath = StrUtil.EMPTY;
		} else {
			normalPath = normalize(path);
			if (isAbsolutePath(normalPath)) {
				// 给定的路径已经是绝对路径了
				return normalPath;
			}
		}

		// 相对于ClassPath路径
		final URL url = ResourceUtil.getResource(normalPath, baseClass);
		if (null != url) {
			// 对于jar中文件包含file:前缀,需要去掉此类前缀,在此做标准化,since 3.0.8 解决中文或空格路径被编码的问题
			return FileUtil.normalize(URLUtil.getDecodedPath(url));
		}

		// 如果资源不存在,则返回一个拼接的资源绝对路径
		final String classPath = ClassUtil.getClassPath();
		if (null == classPath) {
			// throw new NullPointerException("ClassPath is null !");
			// 在jar运行模式中,ClassPath有可能获取不到,此时返回原始相对路径(此时获取的文件为相对工作目录)
			return path;
		}

		// 资源不存在的情况下使用标准化路径有问题,使用原始路径拼接后标准化路径
		return normalize(classPath.concat(Objects.requireNonNull(path)));
	}

三解决办法:

        当前类名.class.getClassLoader().getResourceAsStream("templates/" + templateName); 通过类加载器获取resource下的文件流。

四原因:
        可以看到这个获取的路径是jar包里面文件的路径,通过FileInputStream是无法读取jar里面的文件的,windows系统正常是因为访问的是文件夹里面的文件

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值