Blob 转 OutputStream

StreamingOutput.java

import java.io.IOException;
import java.io.OutputStream;

import javax.ws.rs.WebApplicationException;

/**
 * A type that may be used as a resource method return value or as the entity
 * in a {@link Response} when the application wishes to stream the output.
 * This is a lightweight alternative to a
 * {@link javax.ws.rs.ext.MessageBodyWriter}.
 *
 * @author Paul Sandoz
 * @author Marc Hadley
 * @see javax.ws.rs.ext.MessageBodyWriter
 * @see javax.ws.rs.core.Response
 * @since 1.0
 */
public interface StreamingOutput {

    /**
     * Called to write the message body.
     *
     * @param output the OutputStream to write to.
     * @throws java.io.IOException if an IO error is encountered
     * @throws javax.ws.rs.WebApplicationException
     *                             if a specific
     *                             HTTP error response needs to be produced. Only effective if thrown prior
     *                             to any bytes being written to output.
     */
    void write(OutputStream output) throws IOException, WebApplicationException;
}

转化方法

//通过患者ID查询照片信息
@Override
public StreamingOutput getPatientPhotoByPatientId(String patientId) {
    //获取患者信息里面包含blob类型的照片和指纹信息
    PatInfoNote patInfoNote = strictFindByPrimaryKey(PatInfoNote.class, patientId, "未找到指定患者资料信息patientId");
    if (patInfoNote.getPatientPhotograph() == null) {
        throw new NotFoundException(String.format("患者照片信息不存在patientId[%s]", patientId));
    }
    StreamingOutput streamingOutput = null;
    try {
        //转化方法
        streamingOutput = StringUtils.getStreamingOutputByBlob(patInfoNote.getPatientPhotograph());
    } catch (SystemException e) {
        throw new SystemException("读取患者照片失败");
    }
    return streamingOutput;
}
//-------
public static StreamingOutput getStreamingOutput(final InputStream in) throws IOException {
    StreamingOutput stream = new StreamingOutput() {
        public void write(OutputStream out) throws IOException, WebApplicationException {
            try {
                int read = false;
                byte[] bytes = new byte[1024];

                int readx;
                while((readx = in.read(bytes)) != -1) {
                    out.write(bytes, 0, readx);
                }

            } catch (Exception var4) {
                throw new IOException("文件流读取失败: " + var4.getMessage(), var4);
            }
        }
    };
    return stream;
}

public static StreamingOutput getStreamingOutputByBlob(Blob blob) throws RuntimeException {
    StreamingOutput streamingOutput = null;

    try {
        streamingOutput = getStreamingOutput(blob.getBinaryStream());
        return streamingOutput;
    } catch (Exception var3) {
        throw new RuntimeException("读取数据流失败", var3);
    }
}
原文地址:https://www.cnblogs.com/ms-grf/p/10938950.html