Register now and start sharing your code snippets.
-->

How to read UTF-8 data from an Oracle BLOB column with Java and JDBC

Java posted about 1 year ago by christian

This example works with Oracle:

   1  private String getBlobAsString(Blob blob)
   2  {
   3      StringBuffer result = new StringBuffer();
   4      
   5      if ( blob != null ) 
   6      {
   7          int read = 0;
   8          Reader reader = null;
   9          char[] buffer = new char[1024];
  10                                  
  11          try
  12          {
  13              reader = new InputStreamReader(blob.getBinaryStream(), "UTF-8");
  14  
  15              while((read = reader.read(buffer)) != -1) 
  16              {
  17                  result.append(buffer, 0, read);
  18              }
  19          }
  20          catch(SQLException ex)
  21          {
  22              throw new RuntimeException("Unable to read blob data.", ex);
  23          }
  24          catch(IOException ex)
  25          {
  26              throw new RuntimeException("Unable to read blob data.", ex);
  27          }
  28          finally
  29          {
  30              try { if(reader != null) reader.close(); } catch(Exception ex) {};
  31          }
  32      }
  33      
  34      return result.toString();
  35  }

Then use the method like this:

   1  ResultSet resultSet = your JDBC result set;
   2  
   3  String utf8 = getBlobAsString(resultSet.getBlob("xml"));
   4  

Tagged oracle, blob, utf-8, java