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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM