我知道我可以从src/test/resources加载一个文件:
getClass().getResource("somefile").getFile()
但是我怎么能得到src/test/resources目录的完整路径,即我不想加载一个文件,我只想知道目录的路径?
我知道我可以从src/test/resources加载一个文件:
getClass().getResource("somefile").getFile()
但是我怎么能得到src/test/resources目录的完整路径,即我不想加载一个文件,我只想知道目录的路径?
当前回答
哇,正确答案还不在这里!
MyClass.class.getResource("/somefile");
MyClass.class.getResourceAsStream("/somefile");
https://javachannel.org/posts/how-to-access-static-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,你可以很容易地从资源文件夹(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;
}
在File对象上使用. getabsolutepath()。
getClass().getResource("somefile").getFile().getAbsolutePath()
你可以去你想去的地方
new File(".").getAbsolutePath()
然后,您可以派生src/test/resources的路径 通常只是
new File("src/test/resources")