如何在 JUnit 中获取 src/test/resources 目录的路径? [英] How to get the path of src/test/resources directory in JUnit?
问题描述
我知道我可以从 src/test/resources 加载一个文件:
I know I can load a file from src/test/resources with:
getClass().getResource("somefile").getFile()
但是如何获取src/test/resources目录的完整路径,即我不想加载文件,我只想知道目录的路径?
But how can I get the full path to the src/test/resources directory, i.e. I don't want to load a file, I just want to know the path of the directory?
推荐答案
尝试使用 ClassLoader
类:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("somefile").getFile());
System.out.println(file.getAbsolutePath());
A ClassLoader
负责加载类.每个类都有一个对 ClassLoader
的引用.此代码从资源目录返回一个 File
.对其调用 getAbsolutePath()
返回其绝对Path
.
A ClassLoader
is responsible for loading in classes. Every class has a reference to a ClassLoader
. This code returns a File
from the resource directory. Calling getAbsolutePath()
on it returns its absolute Path
.
ClassLoader
的 Javadoc:http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html
Javadoc for ClassLoader
: http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html
这篇关于如何在 JUnit 中获取 src/test/resources 目录的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!