使用Java8 Base64解码器的IllegalArgumentException
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用Java8 Base64解码器的IllegalArgumentException,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2495字,纯文字阅读大概需要4分钟。
内容图文
![使用Java8 Base64解码器的IllegalArgumentException](/upload/InfoBanner/zyjiaocheng/827/4c59e9764b1e41faac3ebafae8c7b67a.jpg)
我想使用Base64.java来编码和解码文件. Encode.wrap(InputStream)和decode.wrap(InputStream)工作但运行缓慢.所以我使用了以下代码.
public static void decodeFile(String inputFileName,
String outputFileName)
throws FileNotFoundException, IOException {
Base64.Decoder decoder = Base64.getDecoder();
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
byte[] inBuff = new byte[BUFF_SIZE]; //final int BUFF_SIZE = 1024;
byte[] outBuff = null;
while (in.read(inBuff) > 0) {
outBuff = decoder.decode(inBuff);
out.write(outBuff);
}
out.flush();
out.close();
in.close();
}
然而,它总是抛出
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Input byte array has wrong 4-byte ending unit
at java.util.Base64$Decoder.decode0(Base64.java:704)
at java.util.Base64$Decoder.decode(Base64.java:526)
at Base64Coder.JavaBase64FileCoder.decodeFile(JavaBase64FileCoder.java:69)
...
我改变了最后的int BUFF_SIZE = 1024;到最后的int BUFF_SIZE = 3 * 1024;,代码工作.由于“BUFF_SIZE”也用于编码文件,我认为编码的文件有问题(1024%3 = 1,这意味着在文件中间添加了填充).
另外,正如@Jon Skeet和@Tagir Valeev所提到的,我不应该忽略InputStream.read()的返回值.所以,我修改了如下代码.
(但是,我必须提到代码的运行速度比使用wrap()快得多.我注意到了速度差异,因为我在jdk8发布之前很久就编码并集中使用了Base64.encodeFile()/ decodeFile().现在,我的buffed jdk8代码的运行速度和我原来的代码一样快.所以,我不知道wrap()会发生什么…
public static void decodeFile(String inputFileName,
String outputFileName)
throws FileNotFoundException, IOException
{
Base64.Decoder decoder = Base64.getDecoder();
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
byte[] inBuff = new byte[BUFF_SIZE];
byte[] outBuff = null;
int bytesRead = 0;
while (true)
{
bytesRead = in.read(inBuff);
if (bytesRead == BUFF_SIZE)
{
outBuff = decoder.decode(inBuff);
}
else if (bytesRead > 0)
{
byte[] tempBuff = new byte[bytesRead];
System.arraycopy(inBuff, 0, tempBuff, 0, bytesRead);
outBuff = decoder.decode(tempBuff);
}
else
{
out.flush();
out.close();
in.close();
return;
}
out.write(outBuff);
}
}
特别感谢@Jon Skeet和@Tagir Valeev.
解决方法:
我强烈怀疑问题是你忽略了InputStream.read的返回值,而不是检查流的结尾.所以这:
while (in.read(inBuff) > 0) {
// This always decodes the *complete* buffer
outBuff = decoder.decode(inBuff);
out.write(outBuff);
}
应该
int bytesRead;
while ((bytesRead = in.read(inBuff)) > 0) {
outBuff = decoder.decode(inBuff, 0, bytesRead);
out.write(outBuff);
}
我不希望这比使用wrap更快.
内容总结
以上是互联网集市为您收集整理的使用Java8 Base64解码器的IllegalArgumentException全部内容,希望文章能够帮你解决使用Java8 Base64解码器的IllegalArgumentException所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。