Cannot read file within jar file

前端 未结 3 664
半阙折子戏
半阙折子戏 2021-01-22 06:13

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

this is a snippet how I do:

public Set readFile         


        
3条回答
  •  太阳男子
    2021-01-22 06:45

    The javadocs for ClassPathResource state:

    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.

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

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

    public Set readFile() {
        Set setOfEmails = new HashSet();
    
        ClassPathResource cl = new ClassPathResource("myFile.csv");
        URL url = cl.getURL();
        try (BufferedReader br = new BufferedReader(
                                 new InputStreamReader(url.openStream()))) {
    
            Stream 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.

提交回复
热议问题