Is it possible with Rhino Server-side Javascript to locate and read the contents of an arbitrary local file?
Read file with Rhino
Asked Answered
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.)
© 2022 - 2024 — McMap. All rights reserved.