Search code examples
javajavascriptrhinoxlsb

Reading a binary file from the file system as a BLOB to use in rhino with javascript


I'm planing to use SheetJS with rhino. And sheetjs takes a binary object(BLOB if i'm correct) as it's input. So i need to read a file from the system using stranded java I/O methods and store it into a blob before passing it to sheetjs. eg :-

var XLDataWorkBook = XLSX.read(blobInput, {type : "binary"});

So how can i create a BLOB(or appropriate type) from a binary file in java in order to pass it in.

i guess i cant pass streams because i guess XLSX needs a completely created object to process.


Solution

  • I found the answer to this by myself. i was able to get it done this way.
    Read the file with InputStream and then write it to a ByteArrayOutputStream. like below.

    ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 
    

    ...

    buffer.write(bytes, 0, len); 
    

    Then create a byte array from it.

    byte[] byteArray =   buffer.toByteArray();
    

    Finally i did convert it to a Base64 String (which is also applicable in my case) using the "Base64.encodeBase64String()" method in apache.commons.codec.binary package. So i can pass Base64 String as a method parameter.

    If you further need there are lot of libraries(3rd-party and default) available for Base64 to Blob conversion as well.