Selva
Selva

Reputation: 1670

File not found exception in executing javascript in Nashorn

I am newbie to nashorn engine.In my java code i specify the javascript path in filereader but it throws filenotfoundexception in runtime.If i put my javascript in desktop and give that location my code is works.but If i put my javascript function in one of the folder in project it's not work throws file not found exception. Here is my error code

engine.eval(new FileReader("res/nashorn1.js"));

Here is my working code

engine.eval(new FileReader("C:/Users/selva/Desktop/res/nashorn1.js"));

I am using java stand alone application. My Code

public class Nashorn1 {

    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval(new FileReader("C:/Users/selva/Desktop/res/nashorn1.js"));

        Invocable invocable = (Invocable) engine;
        Object result = invocable.invokeFunction("fun1", "Peter Parker");
        System.out.println(result);
        System.out.println(result.getClass());

        invocable.invokeFunction("fun2", new Date());
        invocable.invokeFunction("fun2", LocalDateTime.now());
        invocable.invokeFunction("fun2", new Person());
    }

}

nashorn1.js

var fun1 = function(name) {
    print('Hi there from Javascript, ' + name);
    return "greetings from javascript";
};

var fun2 = function (object) {
    print("JS Class Definition: " + Object.prototype.toString.call(object));
};

Any help would be Greatly Appreciated!!

Upvotes: 0

Views: 1576

Answers (1)

David P. Caldwell
David P. Caldwell

Reputation: 3831

This has nothing to do with Nashorn; it's all about Java and files.

When you specify:

new FileReader("res/nashorn1.js")

this is interpreted as a relative path, so is resolved against your current working directory. If your current working directory happened to be C:/Users/selva/Desktop at the time you executed the program, it would work. (Try it with cd \Users\selva\Desktop or something similar; my DOS is rusty and I have no Windows handy.)

When you specify the whole path, the file is found.

[Footnote: I'm usually very impressed by the Java API specification, and thus very surprised that the java.io.FileReader documentation has no information at all about how the string is interpreted. Oops; I've filed a bug and if they acknowledge it I will update here with effusive praise.]

For your case, it's hard to understand what the "best" solution would be because there's no "problem," exactly; you just need to let Java know where the script can actually be found. Post a follow-up if there's something more specific you need to do.

Upvotes: 1

Related Questions