Classpath resources with Nashorn (JJS)
sundararajan.athijegannathan at oracle.com
Tue Sep 27 14:51:47 UTC 2016
Rhino engine in jdk6 and jdk7 was loaded as bootstrap code. Nashorn is
loaded by extension class loader.
You can check Class.getResourceAsStream's javadoc:
" If this object was loaded by the bootstrap class loader, the method
delegates to ClassLoader.getSystemResourceAsStream(java.lang.String). "
"This method locates the resource through the system class loader (see
With Nashorn/jjs -classpath, you get new class loader (different from
system/launcher loader). And so calling
ClassLoader.getSystemResourceAsStream won't work either.
But, if you do load a class from your jjs -classpath path, then you can
get Class object of it and then call getResourceAsStream on it - like:
jjs -cp foo
jjs> var cl = com.acme.Foo.class; // assuming such as a class from path
Also, you can use __DIR__ variable to load script relative files. The
directory in which your script is stored is available via __DIR__
variable. You can use that to load script relative resources.
Hope this helps,
On 9/26/2016 10:46 AM, Edgar Merino wrote:
> I don't really know if this belongs here, I couldn't find much
> documentation on this issue.
> I've noticed that, when using nashorn's command line utility JJS,
> any resource that is included in the classpath, be it included in a
> JAR or located in a classpath folder, is not available to scripts. A
> simple example:
> |echo "java.lang.Class.class.getResourceAsStream('/test.txt')"|jjs -cp .|
> When a file "test.txt" is included in the current folder (which is
> added to the classpath via the -cp option), this code always returns
> "null". If I run a similar example using java and the jvm directly I
> get the expected resource (an input stream reference). Under rhino I
> get the same results, using a similar example.
> Is this the expected behavior? Is there a way to access resources
> under the classpath in nashorn? This is causing a lot of problems with
> spring contexts for example, everytime I try to load my app context
> from an XML file I get problems because it cannot find some needed
> resources at runtime. This worked fine under rhino, but we are
> planning on migrating to nashorn.
> I found this github wiki, were it states loading resources is only
> possible for nashorn's app class loader:
> This related question is given a useful answer, but it involves
> creating the nashorn engine programatically, instead of using JJS:
> Any help is greatly appreciated.
> Edgar Merino.
More information about the nashorn-dev