Oct 01

Read the bytes from the blob using a ByteArrayOutputStream and then create a String from the resulting byte array.


ByteArrayOutputStream baos = new ByteAttayOutputStream();
byte[] buf = new byte[1024];

InputStream in = blob.getBinaryStream();

int n = 0;
while ((n=in.read(buf))>=0)
{
   baos.write(buf, 0, n);
}

in.close();
byte[] bytes = baos.toByteArray();
String blobString = new String(bytes); 

written by objects \\ tags: , ,


4 Responses to “How do I convert a JDBC Blob to a String?”

  1. Simisani Takobana Says:

    You can achieve the same results by using this code :


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

  2. Zubair Ahmed Says:

    @Simisani Takobana: this technique is for small data set in blob field.. if the data size exceeds then there are chances to get OutOfMemoryExceptions….
    Thanks

  3. Zubair Ahmed Says:


    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();

  4. louiss_louiss Says:

    i have a blob data i want to convert it to String i used both solution that you have mentioned but the result is same like this [] i dont know how to convert it to String

Leave a Reply

You must be logged in to post a comment.