如何获取Java资源目录的绝对路径?

时间:2016-05-27 19:07:21

标签: java unit-testing testng

我正试图找到一种方法来获取junit测试中资源文件夹的绝对路径。

我怀疑不是在资源文件夹中获取文件(我现在该怎么做),但获取资源文件夹的路径。

例如,如果我的资源文件夹中的文件具有以下结构:

/opt/project/view/api/target/classes/
/opt/project/view/api/target/classes/file_in_resources.txt

我想获取位置/opt/project/view/api/target/classes/而不使用丑陋的东西:

URL location = this.getClass().getResource("/file_in_resources.txt");
String path = location.getPath();
String rightPath = path.substring(0, path.lastIndexOf("/"));

这个想法有一个类似this.getClass().getResourcesPath()的方法,但这种方法不存在。

怎么办?

4 个答案:

答案 0 :(得分:0)

如果您的测试类位于同一资源文件夹中,您可以尝试:

URL location = TestClass.class.getProtectionDomain().getCodeSource().getLocation();
String path = location.getPath();
String rightPath = path.substring(0, path.lastIndexOf("/"));

如果资源文件夹不相同,您可以根据其相对位置导航到它,将测试类的位置(使用上面的代码获得)作为参考点。

String adjustedPath = rightPath+"/resources";

答案 1 :(得分:0)

如果一个人应该“有这个问题”的话,可能会有关于赞成和反对意见的长期哲学讨论。但如果你像我一样碰到它,那么这可能是一种方法,如果你想用当前的Java风格(假设:你 file_in_resources.txt < / em>驻留在相应的Unittest标准文件夹src / test / resources中:

private String readFileFromResourcesAsString(String fileName) throws IOException {
    Path filePath = Paths.get("./src/test/resources/yourCustomPathHere/" + fileName);
    return Files.lines(filePath).collect(Collectors.joining());        
}

如果你真的想要坚持 view / api / target / classes / 这个文件夹,你可以使用带有java.net.URI的Paths.get-statement(比如{{3已经提到过):

Paths.get(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI());

此解决方案利用NIO.2周围的最新Java-API(参见Chetan Jadhav CD),如

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

和一些Java 8流API部分将文件内容读入字符串(您可以根据需要更改此部分:))。

Paths.get(".")

是关键所在 - 它可以透明地为您提供当前的工作目录,无论您使用何种操作系统(Windows,Linux,MacOS)。

如果你是一个Spring-User,整个事情就更容易了!请参阅oracle tutorials here

答案 2 :(得分:-1)

答案 3 :(得分:-1)

如果您处于单元测试的上下文中,那么直接引用文件是没有问题的,因为您知道它在哪里并且它不会去任何地方。您可以获取文件URL,然后使用display:none在文件夹结构中向上导航,直到您拥有正确的文件夹。

Path