Adr*_*Ber 31
<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>
Run Code Online (Sandbox Code Playgroud)
此解决方案需要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>
Run Code Online (Sandbox Code Playgroud)
小智 28
在一行中尝试这样来读取test.xml:
String msg = StreamUtils.copyToString( new ClassPathResource("test.xml").getInputStream(), Charset.defaultCharset() );
Run Code Online (Sandbox Code Playgroud)
dao*_*way 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);
}
Run Code Online (Sandbox Code Playgroud)
2021 年更新。
您可以使用Spring的Resource
接口来获取文本文件的内容,然后使用StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());
来获取文本。
示例如下:
@Value("classpath:appVersionFilePath")
private Resource resource;
@GetMapping(value = "/hello")
public HttpResult<String> hello() throws IOException {
String appVersion = StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());
// ...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
57279 次 |
最近记录: |