我使用 spring-boot 开发了一个应用程序,我需要读取包含电子邮件的 csv 文件。
这是我的做法的一个片段:
public Set<String> readFile() {
Set<String> setOfEmails = new HashSet<String>();
try {
ClassPathResource cl = new ClassPathResource("myFile.csv");
File file = cl.getFile();
Stream<String> stream = Files.lines(Paths.get(file.getPath()));
setOfEmails = stream.collect(Collectors.toSet());
} catch (IOException e) {
logger.error("file error " + e.getMessage());
}
return setOfEmails;
}
当我使用 eclipse 执行应用程序时它有效: run As --> spring-boot app
但是当我将 jar 放入容器 docker 中时,方法 readFile() 返回一个空集。
我使用 gradle 来构建应用程序
你有什么想法吗?
The javadocs for ClassPathResource
state:
支持分辨率为java.io.File
如果类路径资源驻留在文件系统中,但不适用于 JAR 中的资源。始终支持 URL 解析。
因此,当资源(CSV 文件)位于 JAR 文件中时,getFile()
将会失败。
解决方案是使用getURL()
相反,然后将 URL 作为输入流打开,等等。像这样的东西:
public Set<String> readFile() {
Set<String> setOfEmails = new HashSet<String>();
ClassPathResource cl = new ClassPathResource("myFile.csv");
URL url = cl.getURL();
try (BufferedReader br = new BufferedReader(
new InputStreamReader(url.openStream()))) {
Stream<String> stream = br.lines();
setOfEmails = stream.collect(Collectors.toSet());
} catch (IOException e) {
logger.error("file error " + e.getMessage());
}
return setOfEmails;
}
如果仍然失败,请检查您是否使用了正确的资源路径。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)