Javascript Nashorn scripting mode: how to write to file

- 1 answer

Ad

I'm writing a shell script to be run with jjs -scripting under Java 8. However, a key requirement is that I need to be able to write to a number of files. (So I can't just print() to stdout and redirect.)

There's handily readFully to read a file, but I don't see any writeFully, which seems odd to me.

I thought probably I could just $EXEC an echo command, but I can't get that to work:

jjs> x='some string'
some string
jjs> $EXEC("echo '"+x+"' >test.out");
some string >test.out

So my next thought is that I have to load up and call the appropriate Java classes, but that seems like it's over-complicating a simple function. What am I missing?

Ad

Answer

Ad

The best I could figure out was to do it via the Java FileWriter class. For example, I had an array of links I needed written to a file:

var FileWriter=Java.type("java.io.FileWriter");
var olinkfile = caldir+"/"+year+"_links.html";
var fw = new FileWriter(olinkfile);
fw.write(links.join("\n"));
fw.write("\n");
fw.close();  // forgetting to close it results in a truncated file

Although it would have been nice for JJS to provide a function to do this directly from JavaScript without having to instantiate the FileWriter class manually, this really isn't too much code. And once you've done it once it seems almost obvious.

Ad
source: stackoverflow.com
Ad