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

前端 未结 11 1277
长发绾君心
长发绾君心 2020-12-01 07:04

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\" constru

11条回答
  •  天命终不由人
    2020-12-01 07:55

    If you really must use only standard libraries, then you just have to expand on Omar's solution a bit. (Apache's IOUtils is basically just a set of convenience methods which saves on a lot of coding)

    You are already able to get the input stream through clobObject.getAsciiStream()

    You just have to "manually transfer" the characters to the StringWriter:

    InputStream in = clobObject.getAsciiStream();
    Reader read = new InputStreamReader(in);
    StringWriter write = new StringWriter();
    
    int c = -1;
    while ((c = read.read()) != -1)
    {
        write.write(c);
    }
    write.flush();
    String s = write.toString();
    

    Bear in mind that

    1. If your clob contains more character than would fit a string, this won't work.
    2. Wrap the InputStreamReader and StringWriter with BufferedReader and BufferedWriter respectively for better performance.

提交回复
热议问题