0

In our application, we are sending an email during registration.
For this we have got an email template stored under /usr/local/email.html

StringWriter writer = new StringWriter();
IOUtils.copy(new FileInputStream(new File("/usr/local/email.html")),writer);
message.setContent(writer.toString(), "text/html");
Transport.send(message);

The above is working fine .

We don't want to hardcode this path (/usr/local/email.html), wanted to keep under classpath

If I keep it under classpath how can I read it?

StringWriter writer = new StringWriter();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("email.html");
IOUtils.copy(is,writer);
message.setContent(writer.toString(), "text/html");
Transport.send(message);

With the above code, I'm getting a java.lang.NullPointerException at

IOUtils.copy(is,writer);
default locale
  • 13,035
  • 13
  • 56
  • 62

3 Answers3

0

If you use getClass().getResourceAsStream with a relative path, the resource is found if it's in the same package as the class.

Alternatively you can use an absolute name like "/some/package/email.html"

Ville Oikarinen
  • 400
  • 1
  • 11
0

Why dont you use

this.getClass().getClassLoader().getResourceAsStream("email.html");
rajesh
  • 3,247
  • 5
  • 31
  • 56
0

Your resource is in a fixed, known location on your classpath, so it's best to use the Class#getResourceAsStream method. You call it on a Class object, and it automatically uses the class's ClassLoader and looks for the resource in the class's package.

For example, if you have a class called com.example.myapp.Emailer and you write:

InputStream is = Emailer.class.getResourceAsStream("email.html");

it will look for com/example/myapp/email.html via the same classloader that's used to load the Emailer class. You'd put email.html in your JAR, in the same place as the compiled Emailer.class file.

I'd specifically recommend not using Thread.currentThread().getContextClassLoader() for this, because the result can vary from thread to thread, and it could potentially be a classloader that isn't able to access the JAR file that holds your resource. You want to make sure you're always using the classloader that actually loads your application's classes, and you accomplish that by calling getResourceAsStream on the Class object of one of your application's classes.

Wyzard
  • 33,849
  • 3
  • 67
  • 87