Spring MVC:从src / main / resources读取文件

时间:2014-02-28 13:49:42

标签: spring-mvc

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

我正在使用

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

isnull

5 个答案:

答案 0 :(得分:77)

Resource resource = new ClassPathResource(fileLocationInClasspath);
InputStream resourceInputStream = resource.getInputStream();

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

答案 1 :(得分:21)

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

df = pd.DataFrame({
'x' : [1,1],
'y' : [1,1],
 })

lof = pd.DataFrame({
'lof' : [2,1],
})


fig= plt.figure(figsize = (4,3), dpi = 200)
plt.scatter(df.x,df.y, s = 8, c =lof.lof)
plt.show()

答案 2 :(得分:13)

以下是加载类路径资源的一种方法。

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

答案 3 :(得分:9)

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

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

然后简单地:

resource.getInputStream();

答案 4 :(得分:0)

  

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

相关问题