Nashorn provides has three functions to output text to the standard output:
The echo() function is the same as the print() function and it works only in scripting mode.
The print()
function is a varargs function.
We can pass any number of arguments to it.
print()
function converts its arguments to string and
prints them separating them by a space.
print()
function prints a new line at the each output.
The following two calls to the print() function returns the same value.
print("Hello", "World!"); // Prints Hello World! print("Hello World!"); // Prints Hello World!
Full source code
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; /* ww w . j a va 2s . c om*/ public class Main { public static void main(String[] args) throws Exception{ ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); String script = "print('Hello', 'World!');"; engine.eval(script); script = "print('Hello World!');"; engine.eval(script); } }
The code above generates the following result.
printf() function uses printf-style to format printing.
It is the same as using the Java method System.out.printf()
:
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; //w w w .j ava 2s . c o m public class Main { public static void main(String[] args) throws Exception{ ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); String script = "printf('%d + %d = %d', 1, 2, 1 + 2);"; engine.eval(script); } }
The code above generates the following result.
The following code shows how to write output of a script execution to a file named jsoutput.txt.
import java.io.File; import java.io.FileWriter; /* w ww . ja v a2 s . c om*/ import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; public class Main { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); File outputFile = new File("jsoutput.txt"); System.out.println("Script output will be written to " + outputFile.getAbsolutePath()); FileWriter writer = new FileWriter(outputFile); ScriptContext defaultCtx = engine.getContext(); defaultCtx.setWriter(writer); String script = "print('Hello custom output writer')"; engine.eval(script); writer.close(); } }
The code above generates the following result.