Byte[] 到 InputStream 或 OutputStream [英] Byte[] to InputStream or OutputStream

查看:40
本文介绍了Byte[] 到 InputStream 或 OutputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库表中有一个 blob 列,为此我必须在 Java 程序中使用 byte[] 作为映射,并且要使用此数据,我必须将其转换为 InputStreamOutputStream.但我不知道这样做时内部会发生什么.任何人都可以简要解释一下我进行此转换时发生了什么?

I have a blob column in my database table, for which I have to use byte[] in my Java program as a mapping and to use this data I have to convert it to InputStream or OutputStream. But I don't know what happens internally when I do so. Can anyone briefly explain me what's happening when I do this conversion?

推荐答案

您可以按如下方式创建和使用字节数组 I/O 流:

You create and use byte array I/O streams as follows:

byte[] source = ...;
ByteArrayInputStream bis = new ByteArrayInputStream(source);
// read bytes from bis ...

ByteArrayOutputStream bos = new ByteArrayOutputStream();
// write bytes to bos ...
byte[] sink = bos.toByteArray();

假设您使用的 JDBC 驱动程序实现了标准 JDBC Blob 接口(并非所有人都这样做),您可以使用 InputStreamOutputStreamInputStream 连接到 Blobcode>getBinaryStream 和 setBinaryStream 方法1,也可以直接获取和设置字节.

Assuming that you are using a JDBC driver that implements the standard JDBC Blob interface (not all do), you can also connect a InputStream or OutputStream to a blob using the getBinaryStream and setBinaryStream methods1, and you can also get and set the bytes directly.

(通常,您应该采取适当的步骤来处理任何异常并关闭流.但是,在上面的示例中关闭 bisbos 是不必要的,因为它们不与任何外部资源相关联;例如文件描述符、套接字、数据库连接.)

(In general, you should take appropriate steps to handle any exceptions, and close streams. However, closing bis and bos in the example above is unnecessary, since they aren't associated with any external resources; e.g. file descriptors, sockets, database connections.)

1 - setBinaryStream 方法实际上是一个 getter.去图.

1 - The setBinaryStream method is really a getter. Go figure.

这篇关于Byte[] 到 InputStream 或 OutputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆