我知道我可以从src/test/resources加载一个文件:

getClass().getResource("somefile").getFile()

但是我怎么能得到src/test/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";

其他回答

在File对象上使用. getabsolutepath()。

getClass().getResource("somefile").getFile().getAbsolutePath()

在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";

我使用的最简单和干净的解决方案,假设测试类的名称是TestQuery1,并且在您的测试文件夹中有一个资源目录,如下所示:

├── java
│   └── TestQuery1.java
└── resources
    └── TestQuery1
        ├── query.json
        └── query.rq

要获得TestQuery1的URI,请执行以下操作:

URL currentTestResourceFolder = getClass().getResource("/"+getClass().getSimpleName());

要获取文件TestQuery1的URI,请执行以下操作:

File exampleDir = new File(currentTestResourceFolder.toURI());
URI queryJSONFileURI = exampleDir.toURI().resolve("query.json");
List<String> lines = Files.readAllLines(Paths.get("src/test/resources/foo.txt"));
lines.forEach(System.out::println);

尝试使用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