String與Blob互轉和file文件與Blob互轉方式
Blob對字符串類型操作
String轉換Blob
可以通過SerialBlob創(chuàng)建Blob對象,SerialBlob下有兩個構造函數(shù),如需創(chuàng)建Blob對象,可以使用 byte[] 類型,先把String轉成byte[]再調用構造函數(shù)。
String 轉換為byte[]
/** * String 轉 byte[] * @param str 請求進入字符串 * @return 返回byte[] 數(shù)組 * @throws Exception 拋出錯誤 */ public byte[] readStream(String str) throws Exception { InputStream inStream=new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8)); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); inStream.close(); return outStream.toByteArray(); }
byte[] 轉為 SerialBlob
Blob blob=new SerialBlob(readStream(str))
Blob轉換Sting
同理,Blob類型轉換為String,就是反過來,先轉換成byte[],再轉換成String。
private String blobToString(Blob blob) throws Exception { InputStream inStream=blob.getBinaryStream(); StringBuffer stringBuffer=new StringBuffer(); try { byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { String str=new String(buffer, 0, len); stringBuffer.append(str); } }catch (Exception e){ throw e; }finally { if(inStream!=null){ inStream.close(); } if(stringBuffer.length()>0){ return stringBuffer.toString(); }else{ return null; } } }
File轉Blob
可以把File文件先轉換成byte[],再通過SerialBlob對象創(chuàng)建
File轉為byte[]
這個方法試試示例,可以去網上找一下File轉換byte[]流的方法
//這個方法只是示例,不推薦這樣使用 public static byte[] getFileByte(File file) throws Exception { byte[] data = null; InputStream in = new FileInputStream(file); data = new byte[in.available()]; in.read(data); in.close(); return data; }
byte[] 轉為 SerialBlob
Blob blob=new SerialBlob(readStream(str))
Blob轉File
可以通過Blob轉成InputStream,再通過讀取的方式轉成File
Blob轉InputStream
InputStream in = blob.getBinaryStream()
InputStream轉File
public void blobToFile(Blob blob,File file) throws Exception { InputStream inStream=null; OutputStream outStream=null; try { outStream = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[2048]; while ((bytesRead = inStream.read(buffer, 0, 2048)) != -1) { outStream.write(buffer, 0, bytesRead); } }catch (Exception e){ throw new Exception(e); }finally { if(outStream!=null){ outStream.close(); } if(inStream!=null){ inStream.close(); } } }
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Java多線程CountDownLatch的實現(xiàn)
本文主要介紹了Java多線程CountDownLatch的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02java中用數(shù)組實現(xiàn)環(huán)形隊列的示例代碼
這篇文章主要介紹了java中用數(shù)組實現(xiàn)環(huán)形隊列的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04解決springboot文件配置端口不起作用(默認8080)
這篇文章主要介紹了解決springboot文件配置端口不起作用(默認8080),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08