问题描述
在我的网络应用程序中,我想读取一个excel文件,它位于src / main / resource / static / doc中,所以我使用
In my web application, I want to read an excel file which is in src/main/resource/static/doc, so I use
String basePath = ClassLoader.getSystemResource()。getPath();
获取资源路径并阅读它。它在我的IDE IDEA中工作,我只是运行它并且可以获得excel。
to get the resource path and read it. It was worked in my IDE IDEA, I just run it and can get the excel.
然而,当我使用 java -jar lab.jar时
运行一个Spring启动项目,它抛出一个NullpointerException,但是当我使用
However, When I use java -jar lab.jar
to run a spring boot project, it threw a NullpointerException, but when I use
String basePath = ClassLoader.getSystemResource (application.properties)。getPath();
并打印出来,我看到/ Users / zhangzhikai / lab-center / target /lab.jar!/BOOT-INF/classes!/application.properties。
and print it, I saw /Users/zhangzhikai/lab-center/target/lab.jar!/BOOT-INF/classes!/application.properties.
为什么我不能从jar中获取excel?
这里是我的文件:
Here is my file dirctionary:
推荐答案
使用时文件
在Java中它必须指向OS文件系统上的物理文件。运行未打包的应用程序时就是这种情况,但是当运行 jar
时,它不是物理文件,因此不起作用(导致错误或空指针异常) )
When using a File
in Java it has to point to a physical file on the OS file system. This is the case when running an unpackaged application, however when running a jar
it isn’t a physical file and as such won’t work (resulting in errors or null pointer exception)
使用Spring的 Resource
类之一来访问资源。在这种情况下,因为它来自类路径,您要使用 ClassPathResource
。然后直接使用 InputStream
来读取文件。
Use one of the Resource
classes of Spring to access the resource. In this case, as it comes from the classpath you want to use a ClassPathResource
. Then directly use the InputStream
to read the file.
Resource input = new ClassPathResource("static/doc/modal/model.xls");
InputStream in = input.getInputStream();
// Use InputStream to read file
这将作为打包和未打包的应用程序工作。不要使用 getFile
,因为这在打包时不起作用。
This will work as packaged and unpackaged application. Don’t use getFile
as that won’t work when packaged.
这篇关于我有一个关于如何运行springboot项目的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!