Nashorn提供了三種函數(shù)來輸出文本到標(biāo)準(zhǔn)輸出:
echo()函數(shù)和print()函數(shù)相同,它僅在腳本模式下工作。
print()
函數(shù)是一個(gè)varargs函數(shù)。我們可以傳遞任意數(shù)量的參數(shù)。
print()
函數(shù)將其參數(shù)轉(zhuǎn)換為字符串,并打印它們,并用空格分隔它們。
print()
函數(shù)在每個(gè)輸出打印一個(gè)新行。
以下兩個(gè)對(duì)print()函數(shù)的調(diào)用返回相同的值。
print("Hello", "World!"); // Prints Hello World! print("Hello World!"); // Prints Hello World!
完整的源代碼
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"); String script = "print("Hello", "World!");"; engine.eval(script); script = "print("Hello World!");"; engine.eval(script); } }
上面的代碼生成以下結(jié)果。
printf()函數(shù)使用printf-style來格式化打印。
它與使用Java方法 System.out.printf()
相同:
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"); String script = "printf("%d + %d = %d", 1, 2, 1 + 2);"; engine.eval(script); } }
上面的代碼生成以下結(jié)果。
以下代碼顯示如何將腳本執(zhí)行的輸出寫入名為jsoutput.txt的文件。
import java.io.File; import java.io.FileWriter; 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(); } }
上面的代碼生成以下結(jié)果。
更多建議: