在我們的程序開發當中,經常會用到java.sql.Blob、byte[]、InputStream之間的相互轉換,但在JDK的API當中,又沒有直接給我們提供可用的API,下面的程序片段主要就是實現它們之間互換的util.
一、byte[]=>Blob
我們可以通過Hibernate提供的表態方法來實現如:
org.hibernate.Hibernate.Hibernate.createBlob(new byte[1024]);
二、Blob=>byte[]
目前沒有找到好一點的API提供,所以只能自已來實現。示例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
/** * 把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[]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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();
以上片段可作為讀者參考。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!