Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient solution for reading CLOB to String, and String to CLOB in Java?

I have a big CLOB (more than 32kB) that I want to read to a String, using StringBuilder. How do I do this in the most efficient way? I can not use the "int length" constructor for StringBuilder since the lenght of my CLOB is longer than a "int" and needs a "long" value.

I am not that confortable with the Java I/O classes, and would like to get some guidance.

Edit - I have tried with this code for clobToString():

private String clobToString(Clob data) {     StringBuilder sb = new StringBuilder();     try {         Reader reader = data.getCharacterStream();         BufferedReader br = new BufferedReader(reader);          String line;         while(null != (line = br.readLine())) {             sb.append(line);         }         br.close();     } catch (SQLException e) {         // handle this exception     } catch (IOException e) {         // handle this exception     }     return sb.toString(); } 
like image 251
Jonas Avatar asked Jan 30 '10 22:01

Jonas


People also ask

How do you cast CLOB to string?

To convert CLOB data type to stringReader r = clob. getCharacterStream(); Read each character one by one from the retrieved Stream of characters and append them to the StringBuilder or StringBuffer.

How do you read a CLOB column in Java?

To read from a CLOB, use the getAsciiStream() or getCharacterStream() method of an oracle. sql. CLOB object to retrieve the entire CLOB as an input stream. The getAsciiStream() method returns an ASCII input stream in a java.

How many characters can CLOB hold?

A CLOB (character large object) value can be up to 2,147,483,647 characters long.


1 Answers

Ok I will suppose a general use, first you have to download apache commons, there you will find an utility class named IOUtils which has a method named copy();

Now the solution is: get the input stream of your CLOB object using getAsciiStream() and pass it to the copy() method.

InputStream in = clobObject.getAsciiStream(); StringWriter w = new StringWriter(); IOUtils.copy(in, w); String clobAsString = w.toString(); 
like image 55
Omar Al Kababji Avatar answered Oct 05 '22 04:10

Omar Al Kababji