Java Reference
In-Depth Information
Listing 2-1 shows the contents of a file named helloscript.js . It contains only one
statement in Nashorn that prints a message on the standard output.
Listing 2-1. The Contents of the helloscript.js File
// helloscript.js
// Print a message
print('Hello from JavaScript!');
Listing 2-2 contains the Java program that executes the script stored in the
helloscript.js file, which should be stored in the current directory. If the script file
is not found, the program prints the full path of the helloscript.js file where it is
expected. If you have trouble executing the script file, try using the absolute path in the
main() method such as C:\scripts\helloscript.js on Windows, assuming that the
helloscript.js file is saved in the C:\scripts directory.
Listing 2-2. Executing a Script Stored in a File
// ReaderAsSource.java
package com.jdojo.script;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ReaderAsSource {
public static void main(String[] args) {
// Construct the script file path
String scriptFileName = "helloscript.js";
Path scriptPath = Paths.get(scriptFileName);
// Make sure the script file exists. If not, print the full
// path of the script file and terminate the program.
if (! Files.exists(scriptPath) ) {
System.out.println(scriptPath.toAbsolutePath() +
" does not exist.");
return;
}
 
Search WWH ::




Custom Search