有趣的是,我在这里做了一些测试,当您Base64InputStream
使用 an读取时,它确实会抛出该异常InputStreamReader
,而不管流的来源,但是当您将其作为二进制流读取时,它可以完美地工作。正如 Trashgod 提到的,Base64 编码是框架化的。InputStreamReader
实际上应该再次调用以查看它是否不再返回任何flush()
数据。Base64InputStream
除了实施您自己的Base64InputStreamReader
或Base64Reader
. 这实际上是一个错误,请参阅基思的回答。
作为一种解决方法,您也可以将其存储在数据库中的 BLOB 而不是 CLOB 中,然后使用PreparedStatement#setBinaryStream()
。它是否存储为二进制数据并不重要。无论如何,您都不希望有如此大的 Base64 数据可索引或可搜索。
更新:由于这不是一个选项,并且让 Apache Commons Codec 人员修复Base64InputStream
我报告为CODEC-101的错误可能需要一些时间,因此您可以考虑使用另一个第 3 方 Base64 API。我在这里找到了一个(公共领域,所以你可以用它做任何你想做的事情,甚至放在你自己的包中),我在这里测试过它,它工作正常。
InputStream base64 = new Base64.InputStream(input, Base64.ENCODE);
更新 2:commons 编解码器的人很快就修复了它。
Index: src/java/org/apache/commons/codec/binary/Base64InputStream.java
===================================================================
--- src/java/org/apache/commons/codec/binary/Base64InputStream.java (revision 950817)
+++ src/java/org/apache/commons/codec/binary/Base64InputStream.java (working copy)
@@ -145,21 +145,41 @@
} else if (len == 0) {
return 0;
} else {
- if (!base64.hasData()) {
- byte[] buf = new byte[doEncode ? 4096 : 8192];
- int c = in.read(buf);
- // A little optimization to avoid System.arraycopy()
- // when possible.
- if (c > 0 && b.length == len) {
- base64.setInitialBuffer(b, offset, len);
+ int readLen = 0;
+ /*
+ Rationale for while-loop on (readLen == 0):
+ -----
+ Base64.readResults() usually returns > 0 or EOF (-1). In the
+ rare case where it returns 0, we just keep trying.
+
+ This is essentially an undocumented contract for InputStream
+ implementors that want their code to work properly with
+ java.io.InputStreamReader, since the latter hates it when
+ InputStream.read(byte[]) returns a zero. Unfortunately our
+ readResults() call must return 0 if a large amount of the data
+ being decoded was non-base64, so this while-loop enables proper
+ interop with InputStreamReader for that scenario.
+ -----
+ This is a fix for CODEC-101
+ */
+ while (readLen == 0) {
+ if (!base64.hasData()) {
+ byte[] buf = new byte[doEncode ? 4096 : 8192];
+ int c = in.read(buf);
+ // A little optimization to avoid System.arraycopy()
+ // when possible.
+ if (c > 0 && b.length == len) {
+ base64.setInitialBuffer(b, offset, len);
+ }
+ if (doEncode) {
+ base64.encode(buf, 0, c);
+ } else {
+ base64.decode(buf, 0, c);
+ }
}
- if (doEncode) {
- base64.encode(buf, 0, c);
- } else {
- base64.decode(buf, 0, c);
- }
+ readLen = base64.readResults(b, offset, len);
}
- return base64.readResults(b, offset, len);
+ return readLen;
}
}
我在这里尝试过,效果很好。