springboot java读取/获取resources相对路径

1、使用org.springframework.core.io.ClassPathResource,各种环境都能读取。(windows/linux通用)

springboot java读取/获取resources相对路径_第1张图片

   public static void main(String[] args) throws IOException {
        //  ClassPathResource classPathResource = new ClassPathResource("static/1.txt");
        Resource resource = new ClassPathResource("static/1.txt");
        //获1.txt的取相对路径
        String path = resource.getFile().getPath();
        System.out.println(path);
        //读取1.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();

    }

2、结合spring注解,使用org.springframework.core.io.ResourceLoader;类的注解。(windows/linux通用)

springboot java读取/获取resources相对路径_第2张图片

package com.tsinkai.ettp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = MiniLegionInitApplication.class) //指定你自己的启动类
@RunWith(SpringRunner.class)
public class EttpCustomApplicationTests {

   @Autowired
    ResourceLoader resourceLoader;


    @Test
    public void testReaderFile() throws IOException {
        Resource resource = resourceLoader.getResource("classpath:templates/1.txt");
        //获1.txt的取相对路径
        String path = resource.getFile().getPath();
        System.out.println(path);
        //读取1.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();
    }
}

搬运地址:https://www.jb51.net/article/195749.htm

你可能感兴趣的:(Java,java)