我知道我可以从src/test/resources加载一个文件:

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

但是我怎么能得到src/test/resources目录的完整路径,即我不想加载一个文件,我只想知道目录的路径?


当前回答

在Spring中,你可以这样使用:

import org.springframework.core.io.ClassPathResource;

// Don't worry when use a not existed directory or a empty directory
// It can be used in @before
String dir = new ClassPathResource(".").getFile().getAbsolutePath()+"/"+"Your Path";

其他回答

我有一个使用JUnit 4.12和Java8的Maven3项目。 为了获得src/test/resources下名为myxml.xml的文件的路径,我在测试用例中这样做:

@Test
public void testApp()
{
    File inputXmlFile = new File(this.getClass().getResource("/myxml.xml").getFile());
    System.out.println(inputXmlFile.getAbsolutePath());
    ...
}

使用IntelliJ IDE在Ubuntu 14.04上测试。 参考这里。

Note

前置/符号是必要的,因为Class.getResource(String)不一定会显示整个文件路径(缺失)以及FileNotFoundException。

如果这是一个spring项目,我们可以使用下面的代码从src/test/resource文件夹中获取文件。

File file = ResourceUtils.getFile(this.getClass().getResource("/some_file.txt"));

我将简单地使用Java 7中的Path

Path resourceDirectory = Paths.get("src","test","resources");

干净利落!

使用Spring,你可以很容易地从资源文件夹(main/resources或test/resources)中读取:

例如,创建一个文件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;
}
List<String> lines = Files.readAllLines(Paths.get("src/test/resources/foo.txt"));
lines.forEach(System.out::println);