有一种方法可以将InputStream
转换为String
并将其编码为base64,对吗?
在我的函数中,我得到InputStream
参数,需要将它插入到我的Oracle数据库表的BLOB字段中。
有没有办法做到这一点?
(我的数据库对象包含保存图像的字符串字段,但我找不到任何将InputStream
转换为base64格式字符串的方法。)
有一种方法可以将InputStream
转换为String
并将其编码为base64,对吗?
在我的函数中,我得到InputStream
参数,需要将它插入到我的Oracle数据库表的BLOB字段中。
有没有办法做到这一点?
(我的数据库对象包含保存图像的字符串字段,但我找不到任何将InputStream
转换为base64格式字符串的方法。)
有一个不错的方法可以使用IOUtils
将输入流转换为字节数组
...
类似这样:
InputStream is;
byte[] bytes = IOUtils.toByteArray(is);
在这里,您可以使用Base64
将Byte Array
转换为String
。
示例代码
String encoded = Base64.getEncoder().encodeToString(bytes);
现在您可以使用您的String
。
您可以使用Base64 API尝试类似以下的操作。
InputStream finput = new FileInputStream(file);
byte[] imageBytes = new byte[(int)file.length()];
finput.read(imageBytes, 0, imageBytes.length);
finput.close();
String imageStr = Base64.encodeBase64String(imageBytes);
使用这个:
String result= IOUtils.toString(inputStream, ENCODING);
根据文档:
toString(byte[] input, String encoding) 使用指定的字符编码将byte[]内容作为字符串获取。
之后进行Base64的编码/解码:
// Encode
String resultBase64Encoded = Base64.getEncoder().encodeToString(result.getBytes("utf-8"));
// Decode
byte[] asBytes = Base64.getDecoder().decode(resultBase64Encoded);
String resultAsStringAgain= String(asBytes, "utf-8")
注意: 我假设您在进行编码/解码部分时使用的是JDK 8。
显然,OP只想将InputStream持久化到数据库中。 您可以直接使用JDBC来实现:
InputStream inputStream = ......;
String sql = "INSERT INTO TABLE_NAME(COLUMN_NAME) values (?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setBlob(1, inputStream);
statement.executeUpdate();
如我所述,您不应该使用String
来处理二进制数据。但是,经过base64编码的数据可以存储为字符串。但由于您的数据库列是blob类型,我建议继续使用byte[]
。
使用IOUtils从InputStream
获取byte[]
:
byte[] bytes = IOUtils.toByteArray(yourInputStream);
byte[] encoded = java.util.Base64.getEncoder().encode(bytes);
然后将其写入数据库。使用jdbc和PreparedStatement编写blob的方法如下:
yourPreparedStatement.setBytes(nIndex, encoded);
如果有人正在寻找没有外部库的解决方案。Java8添加了Base64实用程序类,其中包含getEncoder()
方法。Java9在InputStream
上添加了一个名为readAllBytes()
的花式方法链接到api
因此,现在您可以不使用任何外部库来编写代码
import java.io.InputStream;
import java.util.Base64;
public String encode(InputStream stream) throws IOException {
final var bytes = stream.readAllBytes();
return Base64.getEncoder().encodeToString(bytes);
}