In a unit test I need to import a csv file. This is located in the resources folder, i.e. src/test/resources
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With