springboot中读取资源文件夹下的文件(通用)

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";
}

 

posted @ 2021-08-02 10:08  cxylm  阅读(3357)  评论(0)    收藏  举报