【发布时间】:2014-08-21 09:20:37
【问题描述】:
我正在使用 JUnit 4、Java 8 和 Gradle 1.12。
我有一个需要加载的默认 json 文件。我的项目有src/main/java/(包含项目源)、src/main/resources/(空)、src/test/java/(单元测试源)和src/test/resources/(要加载的json数据文件)目录。 build.gradle 文件位于根目录中。
在我的代码中:
public class UnitTests extends JerseyTest
{
@Test
public void test1() throws IOException
{
String json = UnitTests.readResource("/testData.json");
// Do stuff ...
}
// ...
private static String readResource(String resource) throws IOException
{
// I had these three lines combined, but separated them to find the null.
ClassLoader c = UnitTests.class.getClassLoader();
URL r = c.getSystemResource(resource); // This is returning null. ????
//URL r = c.getResource(resource); // This had the same issue.
String fileName = r.getFile();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName)))
{
StringBuffer fileData = new StringBuffer();
char[] buf = new char[1024];
int readCount = 0;
while ((readCount = reader.read(buf)) != -1)
{
String readData = String.valueOf(buf, 0, readCount);
fileData.append(readData);
}
return fileData.toString();
}
}
}
根据我阅读的内容,这应该可以让我访问资源文件。但是,当我尝试使用 URL 时,会出现空指针异常,因为 getSystemResource() 调用返回 null。
如何访问我的资源文件?
【问题讨论】:
-
你的类路径中有 /src/test/resources 文件夹吗?
-
我对此表示怀疑。不过我没有加载课程。