简体   繁体   English

在Spring Boot JAR中包含一个外部文件

[英]Include an external files in Spring boot JAR

I created a spring boot application which reads an excel file for data to be displayed in the front end so basically its the source of persistent data. 我创建了一个Spring Boot应用程序,该应用程序读取要在前端显示的数据的excel文件,因此基本上是持久数据的源。 I am able to run to correctly from my eclipse but when i create a spring boot jar and run it from the command line it fails as the files are not included in the jar. 我能够从Eclipse正确运行,但是当我创建spring boot jar并从命令行运行它时,由于文件未包含在jar中而失败。

I have tried two location src/main/resources and /src/main/webapp/WEB-INF/external/ but in both cases the files are not included. 我尝试了两个位置src / main / resources和/ src / main / webapp / WEB-INF / external /,但是在两种情况下均不包含文件。

Code : 代码:

private static final String FILE1 = "\\src\\main\\webapp\\WEB-INF\\external\\file1.csv";
private static final String FILE2 = "\\src\\main\\webapp\\WEB-INF\\external\\file2.csv";
private static String currentDirectory = Paths.get(".").toAbsolutePath().toString();
private static String completeAbsolutePath = currentDirectory
                      .substring(0, currentDir.length() - 1)
                      .replace("\\", "\\\\");

reader = new CSVReader(new FileReader(completePath + FILE1))

Error : 错误:

java.io.FileNotFoundException: c:\\delete\\src\\main\\webapp\\WEB-INF\\external\\File1.csv java.io.FileNotFoundException:c:\\ delete \\ src \\ main \\ webapp \\ WEB-INF \\ external \\ File1.csv

Can someone one please help? 有人可以帮忙吗?

You have two problems here: 您在这里有两个问题:

  1. You put the resources under src folder instead of creating a designated resources folder and put it there. 您将资源放在src文件夹下,而不是创建一个指定的资源文件夹并将其放在那里。 To do that you should create a folder called "resources" at the same level as "src" right click the folder, select "Mark Directory As -> Resources Root" 为此,您应该在与“ src”相同的级别上创建一个名为“ resources”的文件夹,右键单击该文件夹,然后选择“将目录标记为-> Resources Root”
  2. You are referring to the file with a relative path. 您正在使用相对路径引用文件。 This may work in eclipse but when you run it as a jar that paths are changed and relative path is not correct anymore. 这可能会在eclipse中起作用,但是当您将其作为jar运行时,路径会更改并且相对路径不再正确。

    To use such a resource you should use the ClassLoader API ClassLoader.getResourceAsStream(String name) to get your resource. 要使用这样的资源,您应该使用ClassLoader API ClassLoader.getResourceAsStream(String name)来获取资源。

    It should look similar to the following: 它看起来应该类似于以下内容:

     reader = new CSVReader(new InputstreamReader(ClassLoader.getResourceAsStream(completePath + 

    FILE1))); FILE1)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM