Spring Boot – 使用ResourceLoader读取文本文件

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

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

该文件位于我的Spring启动项目中: 在此处输入图像描述

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

 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 

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

有人能帮助我吗 ?

提前致谢!

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

详情如下:

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

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

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

在此处输入图像描述

——更新——

完成代码后,问题是您尝试通过FileInputStream读取文件,但实际上它在jar文件中。

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

我遇到了同样的问题,正如@Gipple Lake解释的那样,使用Spring启动你需要将文件加载为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); } 

我在下面添加了“ imports.xmlsrc/main/ressources/imports

将文件放在resources/static ,它将在classpath中并读取如下所示的路径

 import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; Resource resource = new ClassPathResource("/static/pathtosomefile.txt"); resource.getURL().getPath()