Spring项目读取resource下的文件

一、前提条件

  要去读取的文件是存放在project/src/main/resources目录下的,如下图中的test.txt文件。

  

二、使用ClassPathResource类读取

  不管是在哪一层(service、controller..),都可以使用这种方式,甚至是单元测试中,也是可以的。

package cn.ganlixin.demo.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

@RestController
public class TestController {

    @RequestMapping("testFile")
    public String testFile() throws IOException {
        // ClassPathResource类的构造方法接收路径名称,自动去classpath路径下找文件
        ClassPathResource classPathResource = new ClassPathResource("test.txt");
        
        // 获得File对象,当然也可以获取输入流对象
        File file = classPathResource.getFile();
        
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        StringBuilder content = new StringBuilder();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line);
        }
        
        return content.toString();
    }
}

三、单元测试使用ClassPathResource

  单元测试也是可以使用ClassPathResource,但是需要注意:

    1、单元测试的资源目录默认是project/src/test/resources,如果该目录下找到单元测试需要的文件,那么就用找到的文件;

    2、如果在单元测试的资源目录下没有找到单元测试需要的文件,就会去找/project/src/main/resources目录下的同名文件进行操作。

package cn.ganlixin.demo.example;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationConfigTest {

    @Test
    public void testFile() throws IOException {
        final ClassPathResource classPathResource = new ClassPathResource("test.txt");
        final File file = classPathResource.getFile();

        final BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
    }
}

  

猜你喜欢

转载自www.cnblogs.com/-beyond/p/11689291.html