以前有一篇文章专门讲了怎么加载classpath路径的资源文件:
https://cloud.tencent.com/developer/article/1870486
最近接触到另外一种比较新奇的方式。
资源:
加载方式:
package com.chujianyun.web;
import com.alibaba.fastjson.JSON;
import com.chujianyun.libs.json.Cat;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.nio.charset.Charset;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public class WebTest {
/**
* 第一种方式
*/
@Value("${classpath:json/cat.json}")
private ClassPathResource catJson;
@Test
public void testGetResource() throws IOException {
String cat = IOUtils.toString(catJson.getInputStream(), Charset.forName("UTF-8"));
Cat catObj = JSON.parseObject(cat, Cat.class);
Assert.assertEquals("tom",catObj.getName());
}
/**
* 第二种方式
*/
@Test
public void testGetResource2() throws IOException {
Resource resource = new ClassPathResource("json/cat.json");
String cat = IOUtils.toString(resource.getInputStream(), Charset.forName("UTF-8"));
Cat catObj = JSON.parseObject(cat, Cat.class);
Assert.assertEquals("tom",catObj.getName());
}
@Test
public void testGetResource3() throws IOException {
Cat catObj = getJsonObject("json/cat.json",Cat.class);
Assert.assertEquals("tom",catObj.getName());
}
/**
* tip:可以封装到单独的工具类中
*/
private T getJsonObject(String resourcePath, Class clazz) throws IOException {
Resource resource = new ClassPathResource(resourcePath);
String cat = IOUtils.toString(resource.getInputStream(), Charset.forName("UTF-8"));
return JSON.parseObject(cat, clazz);
}
}
当然这种方法可以封装成独立的ResourceUtil工具类,输入资源路径和类型,返回对应的JSON对象。
如果觉得本文对你有帮助,欢迎点赞评论,欢迎关注我,我将努力创作更多更好的文章。