Spring mvc SpringMVC:从src/main/resources读取文件
我有一个maven Spring项目,里面有Spring mvc SpringMVC:从src/main/resources读取文件,spring-mvc,Spring Mvc,我有一个maven Spring项目,里面有xml文件src/main/resources/xyz.xml。如何在SpringMVC控制器中读取它 我正在使用 InputStream is = getClass().getResourceAsStream("classpath:xyz.xml"); 但是是是空的 Resource resource = new ClassPathResource(fileLocationInClasspath); InputStream resourceInpu
xml
文件src/main/resources/xyz.xml
。如何在SpringMVC控制器中读取它
我正在使用
InputStream is = getClass().getResourceAsStream("classpath:xyz.xml");
但是是
是空的
Resource resource = new ClassPathResource(fileLocationInClasspath);
InputStream resourceInputStream = resource.getInputStream();
使用和接口。但是请确保正确复制了resources目录(使用maven),并且没有丢失该目录,例如,如果将测试作为测试上下文的一部分运行。以下是加载类路径资源的一种方法
Resource resource = applicationContext.getResource("classpath:xyz.xml");
InputStream is = resource.getInputStream();
对于基于spring的应用程序,您可以利用ResourceUtils类
File file = ResourceUtils.getFile("classpath:xyz.xml")
您可以向bean添加带有注释
@Value
的字段:
@Value("classpath:xyz.xml")
private Resource resource;
然后简单地说:
resource.getInputStream();
2019年12月14日的最佳工作代码(Spring 5.1.0版发布)
有关更多详细信息,请参见在本例中,fileLocationInClasspath不应以“classpath:”开头。嘿,Robby,这非常有用,但Kenji和我想知道如何从输入流中逐行解析文件。从resources文件夹读取文件–Spring示例文档中说明“主要用于框架内的内部使用。”
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();