How can I load a local file from embedded Rhino?

眉间皱痕 提交于 2019-12-25 05:22:36

问题


I'm using Rhino's context.evaluateString() to run some simple JavaScript from inside of Java. It's textbook right out of the Embedding Javascript guide:

String script = // simple logic
Context c = new ContextFactory().enterContext();
ScriptableObject scope = context.initStandardObjects();
Object o = context.evaluateString(scope, script, "myScript", 1, null);
ScriptableObject result = Context.jsToJava(o, ScriptableObject.class);

I'm not sure this is the current best-practice, because the main Rhino docs appear to be down, but it's working so far.

I'd like to be able to refer to a library in the working directory -- I see that Rhino shell supports load but I don't think this works in the embedding engine.

Is this possible? Is it documented anywhere? Ideally, I'd like to be able to just call something like load('other.js') and have it search directories I specify as a global property.


回答1:


I have a sort-of answer that I don't really like, not least because it exposes what I'm pretty sure is a Rhino bug that drove me crazy for the last half hour:

eval("" + Packages.org.apache.commons.io.FileUtils.readFileToString(
  new java.io.File("/the/local/root", "script.js");
));

{ That "" + ... is how I work around the bug -- if you eval() a Java String (such as is returned from the readFileToString call) without manually coercing it to a JavaScript native string, nothing appears to happen. The call just silently fails. }

This blindly reads an arbitrary file and evals it -- of course, this is what you do when you eval() from the Java side, so I don't worry about it too much.

Anyway, it's not elegant for a number of reasons, but it works. I'd love to hear a better answer!



来源:https://stackoverflow.com/questions/12461648/how-can-i-load-a-local-file-from-embedded-rhino

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!