Java Spring Boot - 使用 ResourceLoader 读取文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41754712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:39:15  来源:igfitidea点击:

Spring Boot - Reading Text File using ResourceLoader

javaspringspring-boot

提问by Greg

I'm trying to read a text file using Spring resource loader like this :

我正在尝试使用 Spring 资源加载器读取文本文件,如下所示:

Resource resource  = resourceLoader.getResource("classpath:\static\Sample.txt");

The file locates here in my Spring boot project: enter image description here

该文件位于我的 Spring boot 项目中: 在此处输入图片说明

It works fine when running the application in eclipse, but when I package the application then run it using java –jar , I get file not found exception :

在 eclipse 中运行应用程序时它工作正常,但是当我打包应用程序然后使用 java –jar 运行它时,我得到文件未找到异常:

java.io.FileNotFoundException: class path resource [static/Sample.txt] cannot be resolved to absolute file path because it does not reside in the
 file system: jar:file:/C:/workspace-test/XXX/target/XXX-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static/Sample.txt

I unziped the Jar file the Sample locates in : XXX-0.0.1-SNAPSHOT\BOOT-INF\classes\static\Sample.txt

我解压了样本所在的 Jar 文件:XXX-0.0.1-SNAPSHOT\BOOT-INF\classes\static\Sample.txt

Can someone help me please ?

有人能帮助我吗 ?

Thanks in advance!

提前致谢!

采纳答案by Gipple Lake

I have checked your code.If you would like to load a file from classpath in a Spring Boot JAR, then you have to use the resource.getInputStream()rather than resource.getFile().If you try to use resource.getFile() you will receive an error, because Spring tries to access a file system path, but it can not access a path in your JAR.

我已经检查了您的代码。如果您想从 Spring Boot JAR 中的类路径加载文件,那么您必须使用resource.getInputStream()而不是resource.getFile()。如果您尝试使用 resource.getFile( ) 您将收到错误消息,因为 Spring 尝试访问文件系统路径,但无法访问 JAR 中的路径。

detail as below:

详情如下:

https://smarterco.de/java-load-file-classpath-spring-boot/

https://smarterco.de/java-load-file-classpath-spring-boot/

回答by Liping Huang

Please try resourceLoader.getResource("classpath:static/Sample.txt");

请尝试 resourceLoader.getResource("classpath:static/Sample.txt");

Working with this code when run with java -jar XXXX.jar

运行时使用此代码 java -jar XXXX.jar

enter image description here

在此处输入图片说明

------ update ------

- - - 更新 - - -

After go through your codes, the problem is you try to read the file by the FileInputStreambut actually it's inside the jar file.

通过你的代码后,问题是你试图通过读取文件,FileInputStream但实际上它在 jar 文件中。

But actually you get the org.springframework.core.io.Resourceso means you cat get the InputStream, so you can do it like new BufferedReader(new InputStreamReader(resource.getInputStream())).readLine();

但实际上你得到org.springframework.core.io.Resourceso 意味着你得到了 InputStream,所以你可以像new BufferedReader(new InputStreamReader(resource.getInputStream())).readLine();

回答by BERGUIGA Mohamed Amine

I had the same problem and as @Gipple Lake explained, with Spring boot you need to load file as inputStream. So bellow I'll add my code as example, where I want to read import.xml file

我遇到了同样的问题,正如@Gipple Lake 所解释的那样,使用 Spring Boot,您需要将文件加载为 inputStream。所以下面我将添加我的代码作为示例,我想在其中读取 import.xml 文件

public void init() {
    Resource resource = new ClassPathResource("imports/imports.xml");
    try {
        InputStream dbAsStream = resource.getInputStream();
        try {
            document = readXml(dbAsStream);
            } catch (SAXException e) {
                trace.error(e.getMessage(), e);
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                trace.error(e.getMessage(), e);
                e.printStackTrace();
            }
    } catch (IOException e) {
        trace.error(e.getMessage(), e);
        e.printStackTrace();
    }
    initListeImports();
    initNewImports();
}

public static Document readXml(InputStream is) throws SAXException, IOException,
      ParserConfigurationException {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

      dbf.setValidating(false);
      dbf.setIgnoringComments(false);
      dbf.setIgnoringElementContentWhitespace(true);
      dbf.setNamespaceAware(true);
      DocumentBuilder db = null;
      db = dbf.newDocumentBuilder();

      return db.parse(is);
  }

I added "imports.xml" bellow src/main/ressources/imports

我在imports.xml下面加了“ ”src/main/ressources/imports

回答by Mohammed Rafeeq

Put the files under resources/static, it will be in classpath and read the path like below

将文件放在 下resources/static,它将在类路径中并读取如下路径

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

Resource resource = new ClassPathResource("/static/pathtosomefile.txt");
resource.getURL().getPath()