1

I am creating a Java Application where in I need to read templates which I am not able to. That is because I am not able to locate the files with proper path.

The code structure is as follows:

The template reading class file is in src/main/java/com.prototype.main while, The templates are residing in src/main/java/templates

Which means, when I create a jar the three folders would be 3 folders: com templates META-INF

Now from any class under the package how can I access the templates? I have tried the following:

  1. new File("/") which in case of web application would have picked from the root directory of the application but in stand alone applications it is the user directory of the system
  2. System.getProperty("user.dir") which gives the project directory
  3. new App().getClass().getName() which shows the package name separated by dot

So if I want to read a template file like /templates/some.xml, how do I get the entire path of this file?

Thanks for any help in advance.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Tarun
  • 939
  • 15
  • 25

2 Answers2

2

An embedded resource is not a File, it is a resource.

You can read these resources using Class#getResource or Class#getResourceAsInputStream depending on your needs.

For example...

URL url = getClass().getResource("/templates/some.xml");

Will return a URL reference to the named resource.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

You can use

InputStream i=this.getClass().getClassLoader().getResourceAsStream("templates/some.xml");

like described in xml FileNotFoundException using slick2D library in java

Community
  • 1
  • 1
Luca Basso Ricci
  • 17,829
  • 2
  • 47
  • 69