2016-12-20 149 views
0

我有一個使用spring啓動的maven項目,項目打包在一個jar文件中。我想要訪問文件夾src/main/resources/中的txt文件或xml文件。我怎樣才能做到這一點?我試過這樣的代碼:URL url = ClassLoader.getSystemResource("...");,但它不適合我。 我在pom.xml文件中添加的資源:Spring BOOT資源

<build> 
    <resources> 
     <resource> 
      <directory>src/main/resources</directory> 
      <includes> 
       <include>**/*.properties</include> 
       <include>**/*.xml</include> 
       <include>**/*.bin</include> 
       <include>**/*.tagger</include> 
       <include>**/*.txt</include> 
      </includes> 
      <filtering>false</filtering> 
     </resource> 
    </resources> 
    <plugins> 
     <plugin> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-maven-plugin</artifactId> 
     </plugin> 
    </plugins> 
</build> 

回答

1

你不需要在pom.xml任何資源的配置,我這樣做。

URL url = this.getClass().getClassLoader().getResource("file_name_goes_here.txt"); 

String fileContent = IOUtils.toString(url); 

請注意,我用org.apache.commons.io.IOUtils來獲取文件內容。

這是我在<build>

<build> 
    <plugins> 
     <plugin> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-maven-plugin</artifactId> 
     </plugin> 
    </plugins> 
</build> 
相關問題