Reputation: 126
I'm reading an Oracle BLOB from DB and want to convert it to a readable String. The BLOB is text encoded to binary and I'm pretty sure that it was encoded with Base64.
My code of reading the BLOB returns a String with unrecognized characters:
public String getStringFromBLOB(String sql) {
...
resultSet.next();
BLOB blob = null;
blob = ((OracleResultSet) resultSet).getBLOB(1);
byte[] bdata = blob.getBytes(1, (int) blob.length());
String tmpStr =new String(bdata);
str = new String(tmpStr.getBytes("UTF8"), "EUC_KR");
return str;
}
Any help will be much appreciated.
Upvotes: 0
Views: 9651
Reputation: 109547
This should do.
byte[] bdata = blob.getBytes(0, (int) blob.length()); // From 0
String data = new String(bdata, "US-ASCII"); // As it claimed to be Base64
byte[] bytes = DatatypeConverter.parseBase64Binary(data);
return new String(bytes, "EUC_KR"); // The original encoding before Base64
Upvotes: 1
Reputation: 7289
If you want it as readable text you can convert it using functions provided in the utl_encode
package.
utl_encode.base64_decode()
Some code sourced elsewhere that uses it:
FUNCTION get_blob_from_base64_string (p_clob CLOB)
RETURN BLOB
IS
l_chunk BLOB; --Chunks of decoded blob that'll be appended
l_result BLOB; --Final blob result to be returned
l_rawout RAW (32767); --Decoded raw data from first pass decode
l_rawin RAW (32767); --Encoded raw data chunk
l_amt NUMBER DEFAULT 7700; --Default length of data to decode
l_offset NUMBER DEFAULT 1; --Default Offset of data to decode
l_tempvarchar VARCHAR2 (32767);
BEGIN
BEGIN
DBMS_LOB.createtemporary (l_result, FALSE, DBMS_LOB.CALL);
DBMS_LOB.createtemporary (l_chunk, FALSE, DBMS_LOB.CALL);
LOOP
DBMS_LOB.READ (p_clob, l_amt, l_offset, l_tempvarchar);
l_offset := l_amt + l_offset;
l_rawin := UTL_RAW.cast_to_raw (l_tempvarchar);
l_rawout := UTL_ENCODE.base64_decode (l_rawin);
l_chunk := to_blob (l_rawout);
DBMS_LOB.append (l_result, l_chunk);
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
NULL;
END;
Source is an Oracle Forums post on base64 decoding a clob (>32K)
Upvotes: 0