我知道我可以从src/test/resources加载一个文件:
getClass().getResource("somefile").getFile()
但是我怎么能得到src/test/resources目录的完整路径,即我不想加载一个文件,我只想知道目录的路径?
我知道我可以从src/test/resources加载一个文件:
getClass().getResource("somefile").getFile()
但是我怎么能得到src/test/resources目录的完整路径,即我不想加载一个文件,我只想知道目录的路径?
当前回答
我将简单地使用Java 7中的Path
Path resourceDirectory = Paths.get("src","test","resources");
干净利落!
其他回答
在File对象上使用. getabsolutepath()。
getClass().getResource("somefile").getFile().getAbsolutePath()
List<String> lines = Files.readAllLines(Paths.get("src/test/resources/foo.txt"));
lines.forEach(System.out::println);
使用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;
}
哇,正确答案还不在这里!
MyClass.class.getResource("/somefile");
MyClass.class.getResourceAsStream("/somefile");
https://javachannel.org/posts/how-to-access-static-resources/
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文件夹。
原来的答案是这样的