SpringBoot读取resources下的文件以及resources的资源路径

发布时间 2023-12-19 15:18:28作者: 五官一体即忢

1.这种可以 但是在容器中获取不到(以下几种都可以只要不在容器)。

InputStream  inputStream = this.getClass().getResourceAsStream("/static/imgs/aha.png");
Properties pps = new Properties();
File file = ResourceUtils.getFile("classpath:defult.properties");
pps.load(new FileReader(file));
Properties pps = new Properties();
InputStream stream = getClass()
                    .getClassLoader()
                    .getResourceAsStream("defult.properties"); 
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
pps.load(br);
//获取resources下文件夹路径
File directory = new File("../项目名/src/main/resources");
String reportPath = directory.getCanonicalPath();
String resource =reportPath+"\\files\\**";
//resource就是所需要的路径 eg: resource="D:\项目名\src\main\resources\files\****"

2.容器和服务器中都可以获取

package com.bme.shed.service;
 
 
 
import com.bme.shed.BmeShedSimulateServiceApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
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.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
 
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class RcvCentInfoParse {
 
    @javax.annotation.Resource
    ResourceLoader resourceLoader;
 
    @Test
    public void testReaderFile() throws IOException {
        Resource resource = resourceLoader.getResource("classpath:dsp.json");
        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();
    }
 
 
}