无法读取jar文件中的文件

我使用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来构build应用程序

你有什么想法吗?

最好的祝福

ClassPathResource的javadoc指出:

如果类path资源驻留在文件系统中,则支持java.io.Fileparsing, 但不支持JAR中的资源 。 始终支持parsing为URL。

所以当资源(CSV文件)在JAR文件中时, getFile()将会失败。

解决方法是使用getURL() ,然后打开URL作为inputstream,等等。 像这样的东西:

 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; } 

如果仍然失败,请检查您是否使用了正确的资源path。

我不使用Spring,但是我发现了ClassPathResource的Javadoc:

如果类path资源驻留在文件系统中,则支持java.io.Fileparsing,但不支持JAR中的资源。 始终支持parsing为URL。

尝试使用getURL()而不是getFile()

使用http://jd.benow.ca/ Jd GUI将你的jar文件放在那里

1)检查文件是否在jar中

2)如果是,那么看到放置它的path/文件夹结构。

3)如果存在是文件夹使用"/<path>/myFile.csv"访问文件

欢呼享受编码