Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a test resource file?

In a unit test I need to import a csv file. This is located in the resources folder, i.e. src/test/resources

like image 439
simpatico Avatar asked Apr 03 '11 12:04

simpatico


People also ask

What are resource files in testing?

a resource is a file in the class path folder structure for your project. this is important because your test resources will be put in your test-classes folder hierarchy and your main resources will be put in your classes folder hierarchy — both in your target folder.

How do I get SRC test resources?

File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file. getAbsolutePath(); System. out.

How do you get resources in Java?

Java programs can use two mechanisms to access resources: Applets use Applet. getCodeBase() to get the base URL for the applet code and then extend the base URL with a relative path to load the desired resource, for example with Applet. getAudioClip(url) . Applications use "well known locations" such as System.

How do I read a file from SRC main resources?

Using Java getResourceAsStream() This is an example of using getResourceAsStream method to read a file from src/main/resources directory. First, we are using the getResourceAsStream method to create an instance of InputStream. Next, we create an instance of InputStreamReader for the input stream.


1 Answers

Probably just useful if you have the file available, for example when doing unit tests - this will not load it out of a jar AFAIK.

URL url = Thread.currentThread().getContextClassLoader().getResource("mypackage/YourFile.csv"); File file = new File(url.getPath()); // where the file is in the classpath eg. <project>/src/test/resources/mypackage/YourFile.csv 
like image 137
AmanicA Avatar answered Oct 08 '22 11:10

AmanicA