0

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?

nIx..
  • 370
  • 1
  • 3
  • 15

1 Answers1

1

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();

Samy
  • 2,387
  • 2
  • 17
  • 31
  • yeah, I think this will work for properties file as its returning stream, I need handle to the File actually. – nIx.. Sep 23 '14 at 11:56
  • You can still read the file contents from stream. If you will have to read the file contents, edited my answer with reading a file content from stream. – Samy Sep 23 '14 at 12:11