如何在Spring中加载资源并将其内容用作字符串

Adr*_*Ber 49 java spring

如何加载Spring资源内容并使用它来设置bean属性或将其作为参数构造函数传递?

该资源包含自由文本.

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)

  • `FileCopyUtils.copyToString()`在这里是一个更好的解决方案,因为它会在使用后关闭InputStream.(两个类的javadoc相互引用,这是显着的差异.) (3认同)
  • 我喜欢这个,因为它使用的是Spring utils:`org.springframework.util.StreamUtils` (2认同)

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)

  • 编程很简单,诀窍是如何从配置文件中执行此操作. (2认同)

Qia*_*yue 8

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)