簡體   English   中英

如何將 java.io.InputStream 轉換為 java.sql.Blob

[英]How to convert java.io.InputStream to java.sql.Blob

如何使用純 Java 將java.io.InputStream轉換為java.sql.Blob

為了響應 tbodt 的建議,我通過 eclipse 調試器運行了以下內容。 調試器顯示myinputstream有內容,但該blob在代碼末尾保持為null 我需要做什么來解決這個問題?

byte[] contents;
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = myinputstream.read(buffer)) != -1){output.write(buffer, 0, count);}//debugger says myinputstream has blksize 16384, buffcount 12742, and max 127394 here
contents = output.toByteArray();
Blob blob = null;
try {blob = new SerialBlob(contents);} 
catch (SerialException e) {e.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}

someObject.setSomeBlobProperty(blob);//debugger says blob is null here

我還通過調試器運行了IOUtils方法,但得到了完全相同的結果,一個null blob但一個填充的myinputstream 我怎樣才能解決這個問題?

Blob blob = null;
try {
    blob = new SerialBlob(IOUtils.toByteArray(myinputstream));//debugger says myinputstream has contents here.
    someObject.setSomeBlobProperty(blob);//debugger says blob is null here
} 
catch (SerialException e) {e.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}

在這兩種情況下,調試器都說myinputstream在指定位置具有blksize 16384、 buffcount 12742 和max 127394,盡管blob buffcount null 運行此代碼后,我還檢查了底層的 MySQL 數據庫,並確認 blob 字段為空。

然后我通過 Eclipse 調試器運行以下命令,這表明在嘗試填充content后,稱為contentbyte[]仍然為空。 因此生成的blob是空的,而輸入inputstream確實繼續具有與上圖相同的內容值:

Blob blob = null;
byte[] content = IOUtils.toByteArray(myinputstream);
try {
    blob = new SerialBlob(content);//debugger says content is empty here
    someObject.setSomeBlobProperty(blob);//debugger says blob is empty here.
}//debugger says myinputstream has the same values as in edit#1
catch (SerialException e) {e.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}

簡單的方法:

contents = IOUtils.toByteArray(in);

但是為此,您需要 Apache Commons IO,這可能很難添加。 如果你不想使用它,或者不能使用它,這里有一種自己做的方法;

ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = input.read(buffer)) != -1)
    output.write(buffer, 0, count);
contents = output.toByteArray();

您可以使用相同的:

Blob xmlForSign=null;
xmlForSign.getBinaryStream();

此方法 getBinaryStream() 返回一個 Inputfilestream。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM