springboot項目打包后,由於jar內部的路徑結構的影響,會導致有些方式讀取資源文件夾下的文件不可用,現分享兩中好用的讀取方式
我采用的springboot打包插件為:
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>${start-class}</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
首先在resources文件夾下放入一個文件,test.txt
讀取資源文件的方法:
方法1:
@Autowired
private ResourceLoader resourceLoader;
@GetMapping("/test1")
public String test1() throws IOException {
Resource resource = resourceLoader.getResource("classpath:test.txt");
InputStream fis = resource.getInputStream();
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String data = null;
while((data = br.readLine()) != null) {
System.out.println(data);
}
br.close();
isr.close();
fis.close();
return "ok";
}
方法二:
@GetMapping("/test2")
public String test2() throws IOException {
Resource resource = new ClassPathResource("test.txt");
InputStream is = resource.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String data = null;
while((data = br.readLine()) != null) {
System.out.println(data);
}
br.close();
isr.close();
is.close();
return "ok";
}