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

前端 未结 11 1298
长发绾君心
长发绾君心 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 08:03

    CLOB are like Files, you can read parts of it easily like this

    // read the first 1024 characters
    String str = myClob.getSubString(0, 1024);
    

    and you can overwrite to it like this

    // overwrite first 1024 chars with first 1024 chars in str
    myClob.setString(0, str,0,1024);
    

    I don't suggest using StringBuilder and fill it until you get an Exception, almost like adding numbers blindly until you get an overflow. Clob is like a text file and the best way to read it is using a buffer, in case you need to process it, otherwise you can stream it into a local file like this

    int s = 0;
    File f = new File("out.txt");
    FileWriter fw new FileWriter(f);
    
    while (s < myClob.length())
    {
        fw.write(myClob.getSubString(0, 1024));
        s += 1024;
    }
    
    fw.flush();
    fw.close();
    

提交回复
热议问题