I know I can load a file from src/test/resources with:
getClass().getResource(\"somefile\").getFile()
But how can I get the full path to th
I have a Maven3 project using JUnit 4.12 and Java8.
In order to get the path of a file called myxml.xml
under src/test/resources
, I do this from within the test case:
@Test
public void testApp()
{
File inputXmlFile = new File(this.getClass().getResource("/myxml.xml").getFile());
System.out.println(inputXmlFile.getAbsolutePath());
...
}
Tested on Ubuntu 14.04 with IntelliJ IDE. Reference here.
If it's a spring project, we can use the below code to get files from src/test/resource folder.
File file = ResourceUtils.getFile(this.getClass().getResource("/some_file.txt"));
With Spring, you can use this:
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";
With Spring you could easily read it from the resources folder (either main/resources or test/resources):
For example create a file: 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;
}
All content in src/test/resources
is copied into target/test-classes
folder. So to get file from test resources during maven build you have to load it from test-classes
folder, like that:
Paths.get(
getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
).resolve(
Paths.get("somefile")
).toFile()
Break down:
getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
- give you URI to target/test-classes
.resolve(Paths.get("somefile"))
- resolves someFile
to target/test-classes
folder.Original anwser is taken from this
The simplest and clean solution I uses, suppose the name of the test class is TestQuery1
and there is a resources
directory in your test
folder as follows:
├── java
│ └── TestQuery1.java
└── resources
└── TestQuery1
├── query.json
└── query.rq
To get the URI of TestQuery1
do:
URL currentTestResourceFolder = getClass().getResource("/"+getClass().getSimpleName());
To get the URI of one of the file TestQuery1
, do:
File exampleDir = new File(currentTestResourceFolder.toURI());
URI queryJSONFileURI = exampleDir.toURI().resolve("query.json");