我知道我可以从src/test/resources加载一个文件:
getClass().getResource("somefile").getFile()
但是我怎么能得到src/test/resources目录的完整路径,即我不想加载一个文件,我只想知道目录的路径?
我知道我可以从src/test/resources加载一个文件:
getClass().getResource("somefile").getFile()
但是我怎么能得到src/test/resources目录的完整路径,即我不想加载一个文件,我只想知道目录的路径?
当前回答
你不需要干扰类加载器。事实上,这是一个不好的习惯,因为当类装入器资源在jar存档中时,它们不是java.io.File对象。
Maven在运行测试之前自动设置当前工作目录,因此您可以使用:
File resourcesDirectory = new File("src/test/resources");
getabsolutepath()将返回正确的值,如果这是你真正需要的。
如果您希望您的测试通过文件系统访问数据,我建议创建一个src/test/data目录。这让你清楚地知道你在做什么。
其他回答
尝试使用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
在一般情况下,不能将资源文件夹中的文件用于测试。原因是资源文件夹中的资源文件存储在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;
}
}
使用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;
}
你不需要干扰类加载器。事实上,这是一个不好的习惯,因为当类装入器资源在jar存档中时,它们不是java.io.File对象。
Maven在运行测试之前自动设置当前工作目录,因此您可以使用:
File resourcesDirectory = new File("src/test/resources");
getabsolutepath()将返回正确的值,如果这是你真正需要的。
如果您希望您的测试通过文件系统访问数据,我建议创建一个src/test/data目录。这让你清楚地知道你在做什么。
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文件夹。
原来的答案是这样的