java.sql.Blob、byte[]、InputStream之間的相互轉換

 在我們的程序開發當中,經常會用到java.sql.Blob、byte[]、InputStream之間的相互轉換,但在JDK的API當中,又沒有直接給我們提供可用的API,下面的程序片段主要就是實現它們之間互換的util. 
一、byte[]=>Blob 
我們可以通過Hibernate提供的表態方法來實現如: 
org.hibernate.Hibernate.Hibernate.createBlob(new byte[1024]); 
二、Blob=>byte[] 目前沒有找到好一點的API提供,所以只能自已來實現。 
示例如下: 
Java代碼  
/** 
* 把Blob類型轉換爲byte數組類型 
* @param blob 
* @return 
*/  
private byte[] blobToBytes(Blob blob) {  
  
BufferedInputStream is = null;  
  
try {  
is = new BufferedInputStream(blob.getBinaryStream());  
byte[] bytes = new byte[(int) blob.length()];  
int len = bytes.length;  
int offset = 0;  
int read = 0;  
  
while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) {  
offset += read;  
}  
return bytes;  
} catch (Exception e) {  
return null;  
} finally {  
try {  
is.close();  
is = null;  
} catch (IOException e) {  
return null;  
}  
}  
}  
  三、InputStream=>byte[] 
Java代碼  
private byte[] InputStreamToByte(InputStream is) throws IOException {    
  
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();    
int ch;    
while ((ch = is.read()) != -1) {    
bytestream.write(ch);    
}    
byte imgdata[] = bytestream.toByteArray();    
bytestream.close();    
  
return imgdata;    
}    
四、byte[] => InputStream byte[]到inputStream之間的轉換很簡單: 
InputStream is = new ByteArrayInputStream(new byte[1024]); 
五、InputStream => Blob 
可通過Hibernate提供的API:Hibernate.createBlob(new FileInputStream(" 可以爲圖片/文件等路徑 ")); 
六、Blob => InputStream 
Blog轉流,可通過提供的API直接調用:new Blob().getBinaryStream(); 
以上片段可作爲讀者參考。 
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/sukyle/archive/2010/05/29/5632713.aspx

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章