我有一个存储在src / main / resources / data中的文件,我想从我的一个组件的Spring Bean类中打开它。我写了以下内容:
private static final String FILE_NAME = "MyFile.csv";
private static final String SEPARATOR = System.getProperty("file.separator");
private static final String FILE_FOLDER = "src" + SEPARATOR + "main" + SEPARATOR
+ "resources" + SEPARATOR + "data" + SEPARATOR;
private static final String FILE_PATH = FILE_FOLDER
+ FILE_NAME;
public boolean readFile() {
String filePath = FILE_PATH;
InputStream is = this.getClass().getResourceAsStream(filePath);
System.out.println(is);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// stuff
}
此类是@Component,其方法由@RestController调用。
使用给定代码,InputStream为null。我怎样才能干净地找到资源?感谢。
答案 0 :(得分:2)
目录src/main/resources
是您资源的基础(“类路径的根”)。
尝试filePath = "/data/MyFile.csv"
请注意,您可以在Windows和Linux上安全地使用'/'。
答案 1 :(得分:1)
您应该将文件打开为InputStream is = this.getClass().getResourceAsStream("data/MyFile.cs")
。这适用于所有操作系统(包括Windows)。如果您遇到问题(例如,在WAR应用程序内),您可以尝试InputStream is = this.getClass().getClassLoader().getResourceAsStream("data/MyFile.cs")
变体。
答案 2 :(得分:1)
正如它在页面上所述:
ApplicationContext appContext =
new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
CustomerService cust =
(CustomerService)appContext.getBean("customerService");
Resource resource =
cust.getResource("classpath:com/mkyong/common/testing.txt");
然后你可以这样做:
InputStream is = resource.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
在您的服务类中:
public class CustomerService implements ResourceLoaderAware {
private ResourceLoader resourceLoader;
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public Resource getResource(String location){
return resourceLoader.getResource(location);
}
}