Writing the Output of Scripts to a File - Java Scripting

Java examples for Scripting:Run Script

Description

Writing the Output of Scripts to a File

Demo Code

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 = null;//from  w  w  w  . j  av a 2s . com
    writer = new FileWriter(outputFile);
    ScriptContext defaultCtx = engine.getContext();
    defaultCtx.setWriter(writer);
    String script = "print('Hello custom output writer')";
    engine.eval(script);
    writer.close();

  }
}

Result


Related Tutorials