How to get the path of src/test/resources directory in JUnit?

前端 未结 14 1826
时光取名叫无心
时光取名叫无心 2020-11-28 01:25

I know I can load a file from src/test/resources with:

getClass().getResource(\"somefile\").getFile()

But how can I get the full path to th

14条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 01:54

    With Spring you could easily read it from the resources folder (either main/resources or test/resources):

    For example create a file: test/resources/subfolder/sample.json

    @Test
    public void testReadFile() {
        String json = this.readFile("classpath:subfolder/sample.json");
        System.out.println(json);
    }
    
    public String readFile(String path) {
        try {
            File file = ResourceUtils.getFile(path);
            return new String(Files.readAllBytes(file.toPath()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return null;
    }
    

提交回复
热议问题