Redirecting Jruby ScriptEngine output to StringWriter

I recently ran into some strange problem while trying to redirect ScriptEngine output for my ruby ​​session. It seems that no matter what Ipass is in my ScriptEngine, it always prints to stdout and stderr. I found this post, but it says it is fixed.

https://scripting.dev.java.net/issues/show_bug.cgi?id=8

scriptContext.setWriter(outWriter); scriptContext.setErrorWriter(errWriter); ruby.setContext(scriptContext); ruby.eval(...) 

I run sbt and use the latest version of jruby-complete.jar, but it still goes to stdout every time. Is this problem really resolved?

I also try to pass eval(...) StringWriter, but I get an array exception when I try to pull a string after that.

+4
source share
1 answer

This seems to work (I am using 1.6.1, released last week):

  ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("jruby"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); engine.getContext().setWriter(pw); engine.eval("puts 'hello'"); System.out.println("output: " + sw.getBuffer()); 
+3
source

Source: https://habr.com/ru/post/1332940/


All Articles