【问题标题】:Unable to read text file from spring boot jar无法从 Spring Boot jar 中读取文本文件
【发布时间】:2017-10-07 11:24:14
【问题描述】:

我正在尝试读取我的 Spring 引导控制台应用程序的资源文件夹中的文件,但我收到了 file not found 异常。

这是我的pom

<resource>
    <directory>src/main/resources</directory>
    <includes>
      <include>**/*.*</include>
    </includes>
  </resource>

这里是个例外:

java.io.FileNotFoundException: class path resource [9.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/abc/Documents/workspace-sts-3.8.4.RELEASE/xyz/target/xyz-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/9.txt

我打开了 xyz-0.0.1-SNAPSHOT.jar 文件,9.txt 在 BOOT-INF/classes 文件夹中。

谢谢, -dj

【问题讨论】:

  • 你读得怎么样?
  • 我忘了提到我正在使用 ClassPathResource。 ClassPathResource 资源 = new ClassPathResource(len + ".txt");文件文件 = resource.getFile();

标签: spring-boot


【解决方案1】:

这是 Spring Boot,让我们使用 ClassPathResource

@Component
public class MyBean {
    @Value("9.txt")
    private ClassPathResource resource;

    @PostConstruct
    public void init() throws IOException {
        Files.lines(resource.getFile().toPath(), StandardCharsets.UTF_8)
            .forEach(System.out::println);
    }
}

更新:因为ClassPathResource 支持解析为 java.io.File 如果类路径资源驻留在文件系统中,但不支持 JAR 中的资源,最好使用这种方式

@Component
public class MyBean {
    @Value("9.txt")
    private ClassPathResource resource;

    @PostConstruct
    public void init() throws IOException {
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
            bufferedReader.lines()
                .forEach(System.out::println);
        }        
    }
}

【讨论】:

  • 我忘了提到我正在使用 ClassPathResource。 ClassPathResource 资源 = new ClassPathResource(len + ".txt");文件文件 = resource.getFile();
【解决方案2】:

这对我有用!

InputStream in = this.getClass().getResourceAsStream("/" + len + ".txt");

因为这不起作用

ClassPathResource resource = new ClassPathResource(len + ".txt"); 
File file = resource.getFile();

【讨论】:

    【解决方案3】:

    在 Spring Boot 中,您可以使用 ResourceLoader 从 Resource 文件夹中读取文件。这是从资源文件夹中读取文件的有效方法。 第一个 Autowire ResourceLoader

    @Autowired
    private ResourceLoader resourceLoader;
    

    然后

    Resource resource = resourceLoader.getResource(CLASSPATH_URL_PREFIX + "9.txt");
    InputStream inputStream = resource.getInputStream();
    

    【讨论】:

      【解决方案4】:

      从 jar 文件中加载文件时,使用 resource.getInputStream() 而不是 resource.getFile()

      【讨论】:

        猜你喜欢
        • 2021-03-05
        • 2019-05-31
        • 2017-06-18
        • 1970-01-01
        • 1970-01-01
        • 2019-02-19
        • 2023-01-10
        • 2020-07-08
        • 2014-05-24
        相关资源
        最近更新 更多