java-如何在Spring中加载资源并将其内容用作字符串
如何加载Spring资源内容并将其用于设置bean属性或将其作为参数构造函数传递?
该资源包含自由文本。
Adrian Ber asked 2020-02-16T13:04:37Z
5个解决方案
31 votes
此解决方案需要Apache Commons IO。
@Parvez建议的另一种没有Apache Commons IO依赖性的解决方案是
Adrian Ber answered 2020-02-16T13:04:59Z
27 votes
在一行中,尝试读取test.xml:
String msg = StreamUtils.copyToString( new ClassPathResource("test.xml").getInputStream(), Charset.defaultCharset() );
N Piper answered 2020-02-16T13:05:19Z
13 votes
只需阅读:
try {
Resource resource = new ClassPathResource(fileLocationInClasspath);
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()),1024);
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
stringBuilder.append(line).append('\n');
}
br.close();
return stringBuilder.toString();
} catch (Exception e) {
LOGGER.error(e);
}
daoway answered 2020-02-16T13:05:39Z
4 votes
这是一种不使用任何外部库的方式。.spring提供的默认库.. environment.properties文件包含键值对...使用$ {key}引用每个值
在我的示例中,我保留数据库道具
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
classpath:environment.properties
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
Chetan answered 2020-02-16T13:06:04Z
1 votes
daoway的回答非常有帮助,并且在Adrian评论之后,我添加了一个类似于daoway的代码的配置片段
从您的组件
@Autowired
private Resource contents;
@PostConstruct
public void load(){
try {
final InputStream inputStream = contents.getInputStream();
//use the stream
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream ,1024);
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
stringBuilder.append(line).append('\n');
}
br.close();
}catch (IOException e) {
LOGGER.error(message);
}
}
Haim Raman answered 2020-02-16T13:06:28Z