2017-06-07 49 views
0

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

这是一个片段我该怎么做:由于运行 - >春季启动应用

但是,当我把罐子到:

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执行应用程序的工作原理容器docker的方法readFile()返回一个空集。

我使用gradle构建应用程序

你有什么想法吗?

问候

回答

2

的Javadoc文件为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; 
} 

如果仍然无法检查您是否使用了正确的资源路径。

+0

谢谢@Stephen C.它适用于我 – Victor

2

我不使用Spring的工作,但我发现ClassPathResource,指出的Javadoc:

支持的分辨率的java.io.File如果类路径的资源所在的文件中系统,但不适用于JAR中的资源。始终支持解析为URL。

请试用getURL()而不是getFile()

0

使用http://jd.benow.ca/ JD GUI有放下你的jar文件和

1)检查该文件是那里的罐子

2)如果是,则看到它被放置在路径/文件夹结构。

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

干杯享受编码