Skip to content

Instantly share code, notes, and snippets.

@smcl
Created August 29, 2016 21:35
Show Gist options
  • Save smcl/b3cce7982d746d2b714b4a6d85e72c8a to your computer and use it in GitHub Desktop.
Save smcl/b3cce7982d746d2b714b4a6d85e72c8a to your computer and use it in GitHub Desktop.
simple example of jjs - utility to invoke the Nashorn engine, which is a Java 8 implementation of es5/6 which can utility Java classes
/*
filerev.js
demo of jjs, takes stdin or list of files and takes entirety of buffer
or list of files, reads them into memory and prints them in reverse order.
awful code, purely to demonstrate the interaction between js and Java in the
Nashorn platform.
example 1:
$ jjs ./filerev.js -- file1.txt file2.txt file3.txt
example 2:
$ cat file.txt | jjs filerev.js
*/
function MultipleFileReader(files) {
this.files = files;
this.currentFileIndex = 0;
this.currentFile = this.openNext();
}
MultipleFileReader.prototype.openNext = function() {
if ( this.currentFileIndex < this.files.length) {
return new java.io.BufferedReader(
new java.io.FileReader(this.files[this.currentFileIndex++])
);
} else {
return null;
}
}
MultipleFileReader.prototype.readLine = function() {
if (this.currentFile == null || this.currentFileIndex > this.files.length) {
return null;
}
var line = this.currentFile.readLine();
if ( line != null && line.length > 0 ) {
return line;
} else {
this.currentFile = this.openNext();
if ( this.currentFile != null ) {
return this.readLine();
}
else {
return null;
}
}
}
function getInputReader(args) {
if (args.length > 0 ) {
return new MultipleFileReader(args);
}
return new java.io.BufferedReader(
new java.io.InputStreamReader(java.lang.System.in)
);
v}
var input = getInputReader(arguments);
var allLines = new java.util.ArrayList();
var line = input.readLine();
while ( line != null && line.length != 0 ) {
allLines.add(line);
line = input.readLine();
}
java.util.Collections.reverse(allLines);
allLines.forEach(function(e, i, a) {
print(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment