我想使用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)
...
在我将
final int BUFF_SIZE = 1024;
更改为final 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。他们为我们提供了宝贵的技术支持。