无法读取 jar 文件中的文件

Vic*_*tor 2 java gradle docker spring-boot

我使用 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;
    } 
Run Code Online (Sandbox Code Playgroud)

当我使用 eclipse 执行应用程序时它有效:run As --> spring-boot app

但是当我将 jar 放入容器 docker 时,方法 readFile() 返回一个空集。

我使用 gradle 来构建应用程序

你有什么想法吗?

Ste*_*n C 6

javadocs中ClassPathResource状态:

支持解析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;
} 
Run Code Online (Sandbox Code Playgroud)

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