2

I have .tpl file containing some static content in a package in src. e.g. src/A/B/C/test.tpl and i'm trying to read it from a class sibling that file (src/A/B/C/Test).

I can't find it in any way! FileReader throws FileNotFoundException.

SOLUTION: Class.getResource() works. Problem is about tpl extension which will not be compiled by default. IDEs have setting to add extensions to compile. I used .html instead of updating compiler settings.

Test.class.getResource("/A/B/C/test.html").getPath().replace("%20", " ") 
3
  • What do you need to do with the file? While it's inside the JAR you can get a URL reference to it or open it as an InputStream, but that's it. If you need a path to the file then you have to move it or extract it out of the JAR at runtime. Commented Dec 11, 2012 at 14:39
  • This is template file. I read it, replace some placeholders and tags then send it to print and flush... Commented Dec 11, 2012 at 14:43
  • If it works you should accept the answer... meta.stackexchange.com/questions/110460/… Commented Dec 12, 2012 at 7:03

2 Answers 2

3

You should use ClassLoader.html#getResourceAsStream

getClassloader().getResourceAsStream(resourcePath); 
Sign up to request clarification or add additional context in comments.

Comments

0

How about moving the file to src/main/resources and then trying something like -

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/test.tpl"); try { context.getClassLoader().getResourceAsStream("test.tpl"); ... } catch (IOException ex) { ex.printStackTrace(); } 

1 Comment

Correct. Using "this" does not work in static context. So you can't do this.getClassLoader(). Just an example. I hadn't seen Aviram's answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.