开发者

Read file with Rhino

Is i开发者_StackOverflowt possible with Rhino Server-side Javascript to locate and read the contents of an arbitrary local file?


Sure is.

from interpreter:

js> readFile('./tmp.txt');

or in code:

var filesz = readFile('./tmp.txt');


For those that want to read a binary file using charCodeAt on the results from readFile don't return the expected values for bytes above 0x7F. If you want to read a binary file, it works better to do something like:

var readBinaryFile=function(path){
    var file=java.io.RandomAccessFile(path,'r');
    var bytes=java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, file.length());
    file.read(bytes);
    file.close();
    return bytes;
}

Which will give you a byte array.

Warning: When you read the bytes from that array it will treat them as signed i.e. 0xFF is interpreted as -1. (If you know an easy way to fix this please comment.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜