CLOB/BLOB与String互转。

1.利用dbms_lob.substr()方法可将对应字段转换成字符串如下:

[html]  view plain  copy
  1. select dbms_lob.substr(content) from NEWS    

该方法有个缺点,当content字段长度超过某个值时,会报错。

2.获取Clob对象,在Java中通过对流处理获取字段内容,该方式没有长度限制

[html]  view plain  copy
  1. select content from NEWS  

[html]  view plain  copy
  1. // 将字CLOB转成STRING类型   
  2.     public String ClobToString(Clob clob) throws SQLException, IOException {   
  3.           
  4.         String reString = "";   
  5.         java.io.Reader is = clob.getCharacterStream();// 得到流   
  6.         BufferedReader br = new BufferedReader(is);   
  7.         String s = br.readLine();   
  8.         StringBuffer sb = new StringBuffer();   
  9.         while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING   
  10.             sb.append(s);   
  11.             s = br.readLine();   
  12.         }   
  13.         reString = sb.toString();   
  14.         return reString;   
  15.     }   

接下来的重点是将从数据库获取到的该字段的对象转换成Clob对象,如下:

[html]  view plain  copy
  1. String content = ClobToString((Clob)obj[1]);  

其中我的obj是从数据库获取的字段数组,obj[1]对应该Clob对象


String s1="走上编程不归路……";
         
  Clob c =newSerialClob(s1.toCharArray());//String 转 clob
  Blob b =newSerialBlob(s1.getBytes("GBK"));//String 转 blob
// 也可以这样不传字符集名称,默认使用系统的
//  Blob b = new SerialBlob(s1.getBytes());

  String clobString = c.getSubString(1, (int) c.length());//clob 转 String
  String blobString =newString(b.getBytes(1, (int) b.length()),"GBK");//blob 转 String
//  前面若没传入字符集名称,则这里也不需要传入,以免出错
//  String blobString = new String(b.getBytes(1, (int) b.length()));
  
        System.out.println(clobString);
        System.out.println(blobString);



    // 将字CLOB转成STRING类型  
  1. String content = ClobToString((Clob)obj[1]); 

  1.     public String ClobToString(Clob clob) throws SQLException, IOException {   
  2.           
  3.         String reString = "";   
  4.         java.io.Reader is = clob.getCharacterStream();// 得到流   
  5.         BufferedReader br = new BufferedReader(is);   
  6.         String s = br.readLine();   
  7.         StringBuffer sb = new StringBuffer();   
  8.         while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由    StringBuffer转成STRING   
  9.             sb.append(s);   
  10.             s = br.readLine();   
  11.         }   
  12.         reString = sb.toString();   
  13.         return reString;   
  14.     }  





http://www.oschina.net/code/snippet_135225_5485
个人分类:  java基础 Oracle

猜你喜欢

转载自blog.csdn.net/bwh0520/article/details/80102154