Search code examples
mavenmaven-resources-plugin

Maven module dependency and resources


I have a maven Project say ProjectA, and there is a class say ClassA in this project which uses the files from resource folder, I am using following way to read from resource:

String fileName = IPToGeoMapper.class.getResource("/resourceFile.txt").getFile();
File resourceFile = new File(fileName);

and it works like charm.

Now, when I create artifact out of this project (I have tried extracting the created jar and it has resourceFile.txt packed in the jar), and use that as a dependency in other project say ProjectB, ClassA no more finds the resourceFile.txt as it tries to browse though resources folder of ProjectB.

I want the best global solution which will work in all the projects where I import artifact created from ProjectA What is the best way to handle this?


Solution

  • Try this way , I am taking an example of reading a property file.

    Properties propfile = new Properties(); propfile.load(PropertyUtils.class.getClassLoader() .getResourceAsStream( "applicationprops.properties"));

    BufferedReader reader = new BufferedReader(new InputStreamReader(ClassA.class.getClassLoader().getResourceAsStream("file.txt"))); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); } System.out.println(out.toString()); //Prints the string content read from input stream reader.close();