Example usage for java.sql Blob getBinaryStream

List of usage examples for java.sql Blob getBinaryStream

Introduction

In this page you can find the example usage for java.sql Blob getBinaryStream.

Prototype

java.io.InputStream getBinaryStream() throws SQLException;

Source Link

Document

Retrieves the BLOB value designated by this Blob instance as a stream.

Usage

From source file:us.daveread.basicquery.BasicQuery.java

/**
 * Writes the contents of BLOB to disk. The name of the file created is
 * based on the column name and the string representation of the
 * BLOB object./*  www  . java2 s .c o  m*/
 * 
 * @param rawColName
 *          The column that contains the BLOB object
 * @param blob
 *          The BLOB object that is written onto the file
 * 
 * @return The name of the file created
 */
private String writeBlob(String rawColName, java.sql.Blob blob) {
    String colName = rawColName;
    FileOutputStream out;
    InputStream in;
    byte[] block;
    int bytesRead;
    String fileName;

    out = null;

    if (colName == null || colName.trim().length() == 0) {
        colName = Resources.getString("msgBLOBColNoName");
    }

    // If the option to display column type is on, strip off col type info
    if (colName.indexOf(' ') > 0) {
        colName = colName.substring(0, colName.indexOf(' '));
    }

    fileName = colName + "." + new java.util.Date().getTime() + ".dat";

    try {
        block = new byte[BLOB_LOAD_BLOCK_SIZE];
        out = new FileOutputStream(fileName, false);
        in = blob.getBinaryStream();
        while ((bytesRead = in.read(block)) > 0) {
            out.write(block, 0, bytesRead);
        }
    } catch (Exception any) {
        LOGGER.error("Failed to write BLOB field value to file [" + fileName + "]", any);
        fileName += " (" + Resources.getString("errFailBLOBWrite", any.getClass().getName(), any.getMessage())
                + ")";
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (Exception any) {
                LOGGER.error("Failed to close the BLOB output file", any);
            }
        }
    }

    return fileName;
}