1.介绍
使用Spring访问和加载类路径中文件内容的各种方法。
2.使用Resource
Resource接口有助于抽象化对低级资源的访问。 实际上,它支持以统一的方式处理各种文件资源。
看一下获取Resource实例的各种方法。
2.1手动地
public Resource loadEmployeesWithClassPathResource() {
return new ClassPathResource("data/employees.json");
}
默认情况下,ClassPathResource通过在线程的上下文类加载器和默认系统类加载器之间进行选择。
但是,也可以指示类加载器直接使用其中之一:
return new ClassPathResource("data/employees.json", this.getClass().getClassLoader());
或通过指定某个类的类加载器:
return new ClassPathResource("data/employees.json", Employee.class.getClassLoader());
请注意,从Resource中,可以轻松地访问Java标准API,例如InputStream或File。
这里要注意的另一件事是上述方法仅适用于绝对路径。 如果要指定相对路径,则可以传递第二类参数。 路径将相对于此类:
new ClassPathResource("../../../data/employees.json", Example.class).getFile();
上面的文件路径是相对于Example类的。
2.2. 使用@Value
可以使用@Value注入资源:
@Value("classpath:data/resource-data.txt")
Resource resourceFile;
读取文件类型:
InputStream inputStream = resourceFile.getInputStream();
byte[] bytes = StreamUtils.copyToByteArray(inputStream);
System.out.println(new String(bytes));
@Value也支持其他前缀,例如file:和url:
2.3使用ResourceLoader
如果想延迟加载资源,可以使用ResourceLoader:
@Resource
private ResourceLoader resourceLoader;
Resource resource = resourceLoader.getResource("classpath:data/resource-data.txt");
InputStream inputStream = resource.getInputStream();
byte[] bytes = StreamUtils.copyToByteArray(inputStream);
System.out.println(new String(bytes));
还要注意,ResourceLoader由所有具体的ApplicationContext实现,也可以简单地依赖ApplicationContext:
@Resource
private ApplicationContext context;
public Resource loadWithApplicationContext() {
return context.getResource("classpath:data/resource-data.txt");
}
3. 使用ResourceUtils
在Spring中还有另一种检索资源的方法,使用ResourceUtils
public File loadWithSpringInternalClass()
throws FileNotFoundException {
return ResourceUtils.getFile("classpath:data/resource-data.txt");
}
应该仔细考虑其基本原理,因为使用上面的标准方法之一可能更好。