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

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

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


当前回答

尝试使用ClassLoader类:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("somefile").getFile());
System.out.println(file.getAbsolutePath());

ClassLoader负责装入类。每个类都有一个对ClassLoader的引用。这段代码从资源目录返回一个File。对其调用getAbsolutePath()将返回其绝对路径。

Javadoc for ClassLoader: http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html

其他回答

在File对象上使用. getabsolutepath()。

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

在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";

src/test/resources中的所有内容都复制到target/test-classes文件夹中。所以在maven构建期间,要从测试资源中获取文件,你必须从test-classes文件夹中加载它,就像这样:

Paths.get(
    getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
).resolve(
    Paths.get("somefile")
).toFile()

分解:

getClass(). getprotectiondomain (). getcodesource (). getlocation (). touri() -给你目标/测试类的URI。 resolve(Paths.get("somefile")) -将somefile解析到target/test-classes文件夹。

原来的答案是这样的

你可以去你想去的地方

new File(".").getAbsolutePath()

然后,您可以派生src/test/resources的路径 通常只是

new File("src/test/resources")

在一般情况下,不能将资源文件夹中的文件用于测试。原因是资源文件夹中的资源文件存储在jar中。它们在文件系统中没有真正的路径。

最简单的解决方法是:

将文件从资源复制到临时文件夹,并获取该临时文件的路径。 使用临时路径执行测试。 删除临时文件。

来自JUnit的TemporaryFolder可以用来创建临时文件,并在测试完成后删除它。番石榴库中的类用于从资源文件夹中复制文件。

请注意,如果我们使用resources文件夹中的子文件夹,就像good文件夹一样,我们不必在资源路径中添加前导/。

public class SomeTest {

    @Rule
    public TemporaryFolder tmpFolder = new TemporaryFolder();


    @Test
    public void doSomethinge() throws IOException {
        File file = createTmpFileFromResource(tmpFolder, "file.txt");
        File goodFile = createTmpFileFromResource(tmpFolder, "good/file.txt");

        // do testing here
    }

    private static File createTmpFileFromResource(TemporaryFolder folder,
                                                  String classLoaderResource) throws IOException {
        URL resource = Resources.getResource(classLoaderResource);

        File tmpFile = folder.newFile();
        Resources.asByteSource(resource).copyTo(Files.asByteSink(tmpFile));
        return tmpFile;
    }

}