【代码小技巧】加载classpath下的文件资源

加载classpath下的文件资源

方式1: Class.getResourceAsStream(name)

指定要加载的资源路径与当前类所在包的路径一致, 如果这个name是以 '/'开头的,那么就会从classpath的根路径下开始查找

private void loadResource() {
		try (InputStream inputStream = this.getClass().getResourceAsStream("/" + FILE_NAME);) {
			String string = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
			System.out.println(string);
		} catch (IOException e) {
			e.printStackTrace();
		}
}
方式2: ClassLoader.getResourceAsStream(name)

指定要加载的资源路径在classpath根路径下的相对路径

private void loadResource() {
		try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(FILE_NAME);) {
			String string = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
			System.out.println(string);
		} catch (IOException e) {
			e.printStackTrace();
		}
}
方式3: 如果使用Spring框架,可以使用ClassPathResource来获取文件资源

指定要加载的资源路径在classpath根路径下的相对路径

	private void loadResource() {
		try (InputStream inputStream = new ClassPathResource(FILE_NAME).getInputStream();) {
			String string = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
			System.out.println(string);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

这种方式其实就是一个上面两种方式的聚合,看下ClassPathResource#getInputStream()

publicClassPathResource(String path) {
	this(path, (ClassLoader) null);
}

public ClassPathResource(String path, @Nullable ClassLoader classLoader) {
	Assert.notNull(path, "Path must not be null");
	String pathToUse = StringUtils.cleanPath(path);
	if (pathToUse.startsWith("/")) {
		pathToUse = pathToUse.substring(1);
	}
	this.path = pathToUse;
	this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
}
	
@Override
public InputStream getInputStream() throws IOException {
	InputStream is;
	if (this.clazz != null) {
		is = this.clazz.getResourceAsStream(this.path);
	}
	else if (this.classLoader != null) {
		is = this.classLoader.getResourceAsStream(this.path);
	}
	else {
		is = ClassLoader.getSystemResourceAsStream(this.path);
	}
	if (is == null) {
		throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
	}
	return is;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值