Umesh Kumar
Umesh Kumar

Reputation: 1397

How to convert Blob object of unknown format to String or xml in java

I have a blob object which I am trying to convert to String or XML format. I am not able to properly serialize it as I don't know the format. How can I convert this blob?

 Blob blob = rs.getBlob(4);
 StringBuffer strOut = new StringBuffer();
 String aux = null;
 BufferedReader br = new BufferedReader(new Inputblob.getBinaryStream()));
try {
    while ((aux = br.readLine()) != null) {
        strOut.append(aux);
    }
    } 
catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

System.out.println(aux);

The output comes in some strange character format:

enter image description here

Upvotes: 2

Views: 8485

Answers (2)

Umesh Kumar
Umesh Kumar

Reputation: 1397

The Blob was in Portable Object Format it means that the data has been serialized so I must deserialise it to a java object.

                        Blob blob = rs.getBlob(4);

                            int blobLength = (int) blob.length();  
                            byte[] blobAsBytes = blob.getBytes(1, blobLength);
                            //release the blob and free up memory. (since JDBC 4.0)
                            blob.free();

                            ByteBuffer buff = ByteBuffer.wrap(blobAsBytes);

                            Object obj = PofSerializerHelper.deserialize1(buff); 

This is was as desired, so issue solved. Thanks

Upvotes: 2

CodePhobia
CodePhobia

Reputation: 1315

As you do not know the structure, the de-serializing of the object into string would not make too much sense.

So if you data set is small. You can use this.

java.sql.Blob ablob = rs.getBlob(1);
String str = new String(ablob.getBytes(1l, (int) ablob.length()));

if the data size exceeds then there are chances to get OutOfMemoryExceptions.

You can try the code above, if that fails you could try this.

StringBuffer strOut = new StringBuffer();
String aux;
// We access to stream, as this way we don't have to use the CLOB.length() which is slower...
// assuming blob = resultSet.getBlob("somefield");
BufferedReader br = new BufferedReader(new InputStreamReader(blob.getBinaryStream()));
while ((aux=br.readLine())!=null) {
strOut.append(aux);
}
return strOut.toString();

Do try this and let me know if these work.

Upvotes: 0

Related Questions