簡體   English   中英

通過Java中的Blob內容創建文件的代碼段

[英]Snippet to create a file from the contents of a blob in Java

我在Oracle 9的數據庫blob列中存儲了一些文件。

我想將那些文件存儲在文件系統中。

這應該很容易,但是我找不到正確的人。

如何在Java中執行此操作?

 PreparedStatement ptmst = ...
 ResutlSet rs = pstmt.executeQuery();
 rs.getBlob();
 // mistery 
 FileOutputStream out = new FileOutputStream();
 out.write(); // etc et c

我知道應該是這樣...我不知道是什么被評論為迷茫

謝謝

編輯

我終於從大衛的問題中得到了這一點。

這是我的懶惰實現:

PreparedStatement pstmt = connection.prepareStatement("select BINARY from MYTABLE");
ResultSet rs = pstmt.executeQuery();
while( rs.next() ) {
    Blob blob = rs.getBlob("BINARY");
    System.out.println("Read "+ blob.length() + " bytes ");
    byte [] array = blob.getBytes( 1, ( int ) blob.length() );
    File file = File.createTempFile("something-", ".binary", new File("."));
    FileOutputStream out = new FileOutputStream( file );
    out.write( array );
    out.close();
}

您想要將blob作為輸入流並將其內容轉儲到輸出流。 因此,“痛苦”應該是這樣的:

Blob blob = rs.getBlob(column);
InputStream in = blob.getBinaryStream();
OutputStream out = new FileOutputStream(someFile);
byte[] buff = new byte[4096];  // how much of the blob to read/write at a time
int len = 0;

while ((len = in.read(buff)) != -1) {
    out.write(buff, 0, len);
}

如果您發現自己做了很多這樣的IO工作,則可以考慮使用Apache Commons IO來處理細節。 然后,設置流之后的所有內容都將是:

IOUtils.copy(in, out);

還有另一種方法可以更快地執行相同的操作。 實際上,上面的答案很好用,但是像IOUtils.copy(in,out)一樣,大型文檔IOUtils.copy(in,out)花費很多時間。 原因是您正在嘗試通過4KB迭代來編寫blob。 Simplier解決方案:

Blob blob = rs.getBlob(column);
InputStream in = blob.getBinaryStream();
OutputStream out = new FileOutputStream(someFile);
byte[] buff = blob.getBytes(1,(int)blob.getLength());
out.write(buff);
out.close();

您的outputStream將一槍寫入blob。

編輯

抱歉,初始帖子上沒有看到“編輯”部分。

暫無
暫無

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

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