【问题标题】:Spring MVC : read file from src/main/resourcesSpring MVC:从 src/main/resources 读取文件
【发布时间】:2014-04-01 13:30:21
【问题描述】:

我有一个 Maven Spring 项目,src/main/resources/xyz.xml 里面有 xml 文件。如何在 Spring MVC 控制器中读取它。

我正在使用

InputStream is = getClass().getResourceAsStream("classpath:xyz.xml");

isnull

【问题讨论】:

标签: spring-mvc


【解决方案1】:
Resource resource = new ClassPathResource(fileLocationInClasspath);
InputStream resourceInputStream = resource.getInputStream();

使用ClassPathResource 和接口resource。但是请确保您正确地复制了资源目录(使用 maven),并且它没有丢失,例如,如果将测试作为测试上下文的一部分运行。

【讨论】:

  • 在这种情况下,fileLocationInClasspath 不应以“classpath:”开头。
【解决方案2】:

这是加载类路径资源的一种方式。

Resource resource = applicationContext.getResource("classpath:xyz.xml");
InputStream is = resource.getInputStream();

【讨论】:

  • 嘿,Robby,这非常有帮助,但 Kenji 和我想知道您将如何从输入流中逐行解析文件。
【解决方案3】:

对于基于 spring 的应用程序,您可以利用 ResourceUtils 类。

File file = ResourceUtils.getFile("classpath:xyz.xml")

【讨论】:

【解决方案4】:

您可以在 bean 中添加带有注释 @Value 的字段:

@Value("classpath:xyz.xml")
private Resource resource;

然后简单地说:

resource.getInputStream();

【讨论】:

    【解决方案5】:

    2019 年 12 月 14 日最佳工作代码(春季版 5.1.0.RELEASE)

    import org.springframework.core.io.Resource;
    import org.springframework.core.io.ClassPathResource;
    
    import java.io.File;
    import java.io.InputStream;
    
    Resource resource = new ClassPathResource("xyz.xml");
    InputStream input = resource.getInputStream();
    File file = resource.getFile();
    

    详情请见this

    【讨论】:

      猜你喜欢
      • 2015-02-26
      • 1970-01-01
      • 2017-02-10
      • 2020-07-24
      • 1970-01-01
      • 2015-03-22
      • 2015-09-16
      • 1970-01-01
      相关资源
      最近更新 更多