使用nashorn脚本将内容追加到文件中-有更好的方法吗?

时间:2018-06-19 13:01:48

标签: java-io nashorn

我设法使用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脚本中是否有更好或更简洁的方法来附加到文件?

参考:https://stackoverflow.com/a/27802475/3043944

0 个答案:

没有答案