java blob转byte_Clob,Blob,InputStream,byte 互转
时间: 2023-07-07 08:19:07 浏览: 279
Java 中 Blob 和 Clob 是 JDBC API 中的两种数据类型,Blob 表示二进制数据,Clob 表示文本数据。InputStream 和 byte[] 则是 Java 中常用的二进制数据处理方式。
下面是 Blob 和 byte[] 之间的相互转换:
1. Blob 转 byte[]
```java
Blob blob = resultSet.getBlob("blob_column");
byte[] data = blob.getBytes(1, (int) blob.length());
```
2. byte[] 转 Blob
```java
byte[] data = ...;
Blob blob = connection.createBlob();
blob.setBytes(1, data);
```
下面是 Blob 和 InputStream 之间的相互转换:
1. Blob 转 InputStream
```java
Blob blob = resultSet.getBlob("blob_column");
InputStream inputStream = blob.getBinaryStream();
```
2. InputStream 转 Blob
```java
InputStream inputStream = ...;
Blob blob = connection.createBlob();
OutputStream outputStream = blob.setBinaryStream(1);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
```
下面是 Blob 和 Clob 之间的相互转换:
1. Blob 转 Clob
```java
Blob blob = resultSet.getBlob("blob_column");
Clob clob = connection.createClob();
Writer writer = clob.setCharacterStream(1);
InputStream inputStream = blob.getBinaryStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
writer.write(new String(buffer, 0, bytesRead, "UTF-8"));
}
```
2. Clob 转 Blob
```java
Clob clob = resultSet.getClob("clob_column");
Blob blob = connection.createBlob();
OutputStream outputStream = blob.setBinaryStream(1);
Reader reader = clob.getCharacterStream();
char[] buffer = new char[4096];
int charsRead = -1;
while ((charsRead = reader.read(buffer)) != -1) {
outputStream.write(new String(buffer, 0, charsRead).getBytes("UTF-8"));
}
```
阅读全文