博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

CLOB与String对象互转

Posted on 2011-08-16 13:56  三块石头  阅读(722)  评论(0)    收藏  举报

在MySQL中用了TEXT字段,从数据库取出时需要转为字符串,存入时需要转为BLOB对象。写了如下代码:

package com.flyingzl.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;

import org.hibernate.Hibernate;

public class Helper {
/**
* Blob字段转化成字符串
*
@param blob
*
@return
*
@throws Exception
*/
public static String blob2String(Blob blob)throws Exception{
BufferedReader in
= new BufferedReader(
new InputStreamReader(blob.getBinaryStream(),"UTF-8"));
StringBuffer buffer
= new StringBuffer();
String line
= "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
in.close();
return buffer.toString();
}

/**
* 字符串转为Blob对象
*
@param content
*
@return
*/
public static Blob string2blob(String content){
Blob blob
=null;
try {
InputStream in
= new ByteArrayInputStream(content.getBytes("UTF-8"));
blob
=Hibernate.createBlob(in);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return blob;
}

}