无法读取jar文件中的文件 [英] Cannot read file within jar file

查看:379
本文介绍了无法读取jar文件中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用spring-boot开发了一个应用程序,我需要阅读一个包含电子邮件的csv文件。

I developped an application using spring-boot, I need to read a csv file that contain emails.

这是我的代码段:

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执行应用程序时,它可以工作:运行方式-> spring -boot app

It works when I execute the application using eclipse: run As --> spring-boot app

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

But when I put the jar into a container docker the method readFile() return an empty set.

我使用gradle构建应用程序

I use gradle for build the application

您有什么想法吗?

最诚挚的问候

推荐答案

ClassPathResource 的Javadoc状态:

The javadoc for ClassPathResource states:


如果类路径资源位于文件系统中,则支持解析为 java.io.File ,但是而不是JAR中的资源。始终支持将解析作为URL。

Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR. Always supports resolution as URL.

因此,当资源(CSV文件)位于JAR文件中时, getFile()将会失败。

So when the resource (the CSV file) is in a JAR file, getFile() is going to fail.

解决方案是使用 getURL(),然后打开URL作为输入流,等等。像这样:

The solution is to use getURL() instead, then open the URL as an input stream, etcetera. Something like this:

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

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

If it still fails check that you are using the correct resource path.

这篇关于无法读取jar文件中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆