Spring boot 无法从spring启动jar读取文本文件

Spring boot 无法从spring启动jar读取文本文件,spring-boot,Spring Boot,我试图读取Spring引导控制台应用程序的resources文件夹中的一个文件,但我得到了一个file not found异常 这是我的pom <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> </resource&

我试图读取Spring引导控制台应用程序的resources文件夹中的一个文件,但我得到了一个file not found异常

这是我的pom

<resource>
    <directory>src/main/resources</directory>
    <includes>
      <include>**/*.*</include>
    </includes>
  </resource>
我打开了xyz-0.0.1-SNAPSHOT.jar文件,9.txt文件位于BOOT-INF/classes文件夹中

谢谢,
-dj

现在是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);
    }
}
更新:因为如果类路径资源位于文件系统中,则支持解析为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);
        }        
    }
}

这对我有用

InputStream in = this.getClass().getResourceAsStream("/" + len + ".txt");
因为这不起作用

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

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

@Autowired
private ResourceLoader resourceLoader;
然后


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

您是如何读取的?我忘了提到我使用的是ClassPathResource。ClassPathResource=newClassPathResource(len+“.txt”);File File=resource.getFile();可能与我忘记提到我正在使用ClassPathResource的内容重复。ClassPathResource=newClassPathResource(len+“.txt”);File File=resource.getFile();
@Autowired
private ResourceLoader resourceLoader;
Resource resource = resourceLoader.getResource(CLASSPATH_URL_PREFIX + "9.txt");
InputStream inputStream = resource.getInputStream();