Java SQL Blob readBlob(Blob blob)

Here you can find the source of readBlob(Blob blob)

Description

read Blob

License

Apache License

Declaration

static byte[] readBlob(Blob blob) 

Method Source Code

//package com.java2s;
/**/*from  ww  w  .  j  a v  a 2s .  c  o  m*/
 * Copyright (C) 2008 Mathieu Carbou <mathieu.carbou@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.BufferedInputStream;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;

import java.io.Writer;

import java.sql.Blob;

import java.sql.SQLException;

public class Main {
    static byte[] readBlob(Blob blob) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            copy(new BufferedInputStream(blob.getBinaryStream()), baos);
            return baos.toByteArray();
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private static void copy(InputStream is, OutputStream os) {
        byte[] buffer = new byte[4096];
        int count;
        try {
            while ((count = is.read(buffer)) != -1) {
                os.write(buffer, 0, count);
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            close(is);
            close(os);
        }
    }

    private static void copy(Reader is, Writer os) {
        char[] buffer = new char[4096];
        int count;
        try {
            while ((count = is.read(buffer)) != -1) {
                os.write(buffer, 0, count);
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            close(is);
            close(os);
        }
    }

    private static void close(Closeable closeable) {
        try {
            closeable.close();
        } catch (Exception ignored) {
        }
    }
}

Related

  1. getDataFromBlob(Blob b)
  2. getLongBlobTypeString(Connection conn)
  3. getString(Blob blob)
  4. getStringValue(Blob blob)
  5. isBlob(Object object)
  6. readBytes(Blob blob, byte[] defaultValue)
  7. safeFree(Blob blob)
  8. safeFree(Blob blob)
  9. toByteArray(Blob blob)