如何加载Spring资源内容并使用它来设置bean属性或将其作为参数构造函数传递?
资源包含自由文本。
发布于 2012-12-24 22:58:37
<bean id="contents" class="org.apache.commons.io.IOUtils" factory-method="toString">
<constructor-arg value="classpath:path/to/resource.txt" type="java.io.InputStream" />
</bean>此解决方案需要Apache Commons IO。
@Parvez建议的另一种不依赖Apache Commons IO的解决方案是
<bean id="contents" class="java.lang.String">
<constructor-arg>
<bean class="org.springframework.util.FileCopyUtils" factory-method="copyToByteArray">
<constructor-arg value="classpath:path/to/resource.txt" type="java.io.InputStream" />
</bean>
</constructor-arg>
</bean>发布于 2017-12-01 18:51:38
在一行代码中,尝试读取test.xml:
String msg = StreamUtils.copyToString( new ClassPathResource("test.xml").getInputStream(), Charset.defaultCharset() );发布于 2012-12-25 17:40:13
只需读一读:
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);
}https://stackoverflow.com/questions/14022839
复制相似问题