【问题标题】:I have an problem about how to run a springboot project我对如何运行 springboot 项目有疑问
【发布时间】:2019-03-26 08:03:36
【问题描述】:

在我的网络应用程序中,我想读取 src/main/resource/static/doc 中的 excel 文件,所以我使用了

String basePath = ClassLoader.getSystemResource("").getPath();

获取资源路径并读取它。它在我的 IDE IDEA 中运行,我只需运行它即可获得 excel。

但是,当我使用java -jar lab.jar 运行spring boot 项目时,它抛出了NullpointerException,但是当我使用时

String basePath = ClassLoader.getSystemResource("application.properties").getPath();

打印出来,我看到了/Users/zhangzhikai/lab-center/target/lab.jar!/BOOT-INF/classes!/application.properties。

为什么我无法从 jar 中获取 excel?

这是我的文件目录:

【问题讨论】:

  • 直接使用这个 File file = new ClassPathResource("/doc/modal/model.xls").getFile();
  • 因为打包成JAR就没有这种东西了。 @this_is_om_vm 的解决方案也不起作用,因为在打包的应用程序中没有指向该资源的 File。相反,只需使用ClassPathResource 来读取InputStream 而不是File。
  • @this_is_om_vm 我想读取 modal.xls 并创建新文件 new.xls 到 doc/temp,我可以获取 doc 路径吗?
  • @M.Deinum 谢谢你的回复。你能帮我写代码吗?我很不明白。

标签: java spring-boot jar


【解决方案1】:

在 Java 中使用 File 时,它必须指向操作系统文件系统上的物理文件。运行未打包的应用程序时会出现这种情况,但是在运行 jar 时,它不是物理文件,因此无法正常工作(导致错误或空指针异常)

使用 Spring 的 Resource 类之一来访问资源。在这种情况下,由于它来自您要使用的类路径ClassPathResource。然后直接使用InputStream 读取文件。

Resource input = new ClassPathResource(“static/doc/modal/model.xls”);
InputStream in = input.getInputStream();
// Use InputStream to read file

这将作为打包和未打包的应用程序工作。不要使用getFile,因为它在打包时不起作用。

【讨论】:

  • 这对我使用 Open PDF(pdf 库)+ Elastic Beanstalk 引用 Spring Boot 中的图像很有用。得到输入后,我正在执行以下操作Image.getInstance(input.getURI().toString());
【解决方案2】:
    File xlsfile = new ClassPathResource("/doc/modal/model.xls").getFile();
     //also check the path
    //String currentPath = xlsfile .getAbsolutePath(); 
    File newXls=new File("classpath:static/doc/temp");
    newXls=xlsfile;

正如评论中讨论的那样,希望这可能对您有所帮助。

【讨论】:

  • java.io.FileNotFoundException: 类路径资源 [doc/modal/model.xls] 无法解析为 URL,因为它不存在
  • 对不起,您需要将其替换为 File xlsFile= new File("classpath:static/doc/modal/model.xls");
  • 非常感谢,它确实有效,如果我想创建一个新的 excel,只需 new File("classpath:static/doc/temp/new.xls") ?但它不存在。
  • 只使用 File("classpath:static/doc/temp/new") ...不要附加文件扩展名
  • 这行不通,因为首先它在打包为存档时不是文件资源,并且File 不理解classpath: 作为前缀,因为它是特定于 Spring 的。
猜你喜欢
  • 2019-12-13
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 2017-02-22
  • 2019-05-06
  • 1970-01-01
  • 2020-10-17
  • 2021-05-23
相关资源
最近更新 更多