Spring MVC : read file from src/main/resources

前端 未结 5 1561
梦谈多话
梦谈多话 2020-12-03 06:30

I have a maven Spring project, there is xml file inside src/main/resources/xyz.xml. How can I read it inside spring MVC controller.

I am us

相关标签:
5条回答
  • 2020-12-03 06:59

    Here is one way of loading classpath resources.

    Resource resource = applicationContext.getResource("classpath:xyz.xml");
    InputStream is = resource.getInputStream();
    
    0 讨论(0)
  • 2020-12-03 07:06
    Resource resource = new ClassPathResource(fileLocationInClasspath);
    InputStream resourceInputStream = resource.getInputStream();
    

    using ClassPathResource and interface resource. But make sure you are copying the resources directory correctly (using maven), and its not missing, for example if running tests as part of test context.

    0 讨论(0)
  • 2020-12-03 07:07

    For spring based application you can take advantage of ResourceUtils class.

    File file = ResourceUtils.getFile("classpath:xyz.xml")
    
    0 讨论(0)
  • 2020-12-03 07:12

    You can add a field with annotation @Value to your bean:

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

    And then simply:

    resource.getInputStream();
    
    0 讨论(0)
  • 2020-12-03 07:22

    Best working code in Dec 14, 2019 (Spring version 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();
    

    See this for more details

    0 讨论(0)
提交回复
热议问题