我设法使用Java的File API(Java.IO)以nashorn脚本创建和写入文件,如下所示。
function appendToFile(url, text, createFile){
var fileRet;
var imports = new JavaImporter(java.net, java.lang, java.io); // not all these imports needed. I used this model from another stackoverflow thread.
with (imports) {
try {
fileObj = new File(url);
if(createFile){
fileObj.createNewFile(); // Maybe not relevant for other users.
}
fileRet = fileObj.toURI().toURL();
var bw = new BufferedWriter(new FileWriter(fileObj, true));
var out = new PrintWriter(bw, true); // I enabled autoflush becuase I call this append inside a loop and i was getting an error which is linked to nashorn script functions not being thread safe.
out.println(text)
out.close();
bw.close();
} catch (e) {
print(e);
}
}
return fileRet;
}
我的问题:在nashorn脚本中是否有更好或更简洁的方法来附加到文件?