java - 我想部署在类路径中包含一些文件的 jar

标签 java spring-boot classpath

当我使用此命令 java -jar myapp.jar 执行 jar 时,我遇到了 FileNotFoundException

我的项目是一个基本的 Gradle java 应用程序。我将文件放在 ROOT/src/main/resources/testfile/test1.txt 中。我尝试在 IDE 中运行代码以使用类路径检查文件是否存在。

File file = ResourceUtils.getFile("classpath:testfile/test1.txt");
System.out.println(file.exists());

这是真的,但是当我执行作为命令“gradle build”的结果的构建文件时,我遇到了 FileNotFoundException。当我取消归档 jar 时,我可以看到文件(\BOOT-INF\classes\testfile\test1.txt)

其实我想用示例文件部署spring boot jar,我会放初始化的代码。请帮忙。谢谢。

最佳答案

假设您实际上想要读取文件而不是尝试使用类加载器来寻址资源:

    InputStream in = getClass().getResourceAsStream("/testfile/test1.txt");
    BufferedReader reader = new BufferedReader( new InputStreamReader( in ) );
    String line = null;
    while( (line = reader.readLine() ) != null )
      System.out.println("Line: " + line);

对我有用

关于java - 我想部署在类路径中包含一些文件的 jar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58339454/

相关文章:

java - 具有集合的JPA实体针对分离成员上的contains方法返回false

java - PHP 中的三层方法

java - 在 Spring Boot 中使用 application.yml 配置嵌入式 Tomcat 的日志记录

java - Eclipse 中缺少 JBoss 服务器运行时库

Windows 上带有通配符的 java 类路径 : Requires semi-colon at the end

java - 位旋转 : interleave bytes in word with zero bytes using bitwise operators (<<, |、& 等)

java - 将Java未完成的项目添加到SBT依赖项

spring - 为 Spring-boot 应用程序捕获应用程序停止事件

spring - Zuul代理动态发现路由

java - 将依赖项添加到 jar 类路径 list