Spring 中讀取文件-ResourceLoaderAware
概述
- Spring ResourceLoader為我們提供了一個統一的getResource()方法來通過資源路徑檢索外部資源。從而將資源或文件(例如文本文件、XML文件、屬性文件或圖像文件)加載到Spring應用程序上下文中的不同實現
資源(Resource)接口
- Resource是Spring中用於表示外部資源的通用接口。
- Spring為Resource接口提供了以下6種實現。
- UrlResource
- ClassPathResource
- FileSystemResource
- ServletContextResource
- InputStreamResource
- ByteArrayResource
- 我們可以指定不同的前綴來創建路徑以從不同位置加載資源
ResourceLoader
- getResource()方法將根據資源路徑決定要實例化的Resource實現。 要獲取ResourceLoader的引用,請實現ResourceLoaderAware接口。
Resource banner = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");
ApplicationContext加載資源
- 在Spring中,所有應用程序上下文都實現ResourceLoader接口。因此,所有應用程序上下文都可用於獲取資源實例。
- 要獲取ApplicationContext的引用,請實現ApplicationContextAware接口。
Resource banner = ctx.getResource("file:c:/temp/filesystemdata.txt");
在springboot中使用示例
@Component
public class CustomResourceLoader implements ResourceLoaderAware {
@Autowired
private ResourceLoader resourceLoader;
public void showResourceData() throws IOException
{
//This line will be changed for all versions of other examples
Resource banner = resourceLoader.getResource("file:E:\\refreshlog\\log1.txt");
InputStream in = banner.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
reader.close();
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
try {
showResourceData();
} catch (IOException e) {
e.printStackTrace();
}
}
}
參考
- Spring ResourceLoaderAware – Read file in Spring