使用org.apache.commons.codec.binary.Base64InputStream解码Base64文件

时间:2014-10-16 06:18:08

标签: java stream base64 apache-commons

Hello Stackoverflowers,

org.apache.commons.codec.binary.Base64InputStream我遇到了一个奇怪的问题:它给了我完全相同的原始Base64编码字节流。

使用的代码是:

  InputStream is = new BufferedInputStream(
                        new FileInputStream(
                           new File("/tmp/inputFile")));
  try
  {
    File decodedFile = new File("/tmp/file.dec");
    OutputStream os = new BufferedOutputStream(new FileOutputStream(decodedFile));
    try
    {
      Base64InputStream b64is = new Base64InputStream(is); 
      try
      {
        byte[] buff = new byte[2048];
        int count;
        while ((count = is.read(buff)) > 0)
        {
          os.write(buff, 0, count);
        }
      } finally
      {
        b64is.close();
      }
    } finally
    {
      os.close();
    }
  }
  finally
  {
    is.close();
  }

如果inputFile包含Base64编码的字符串(例如0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAOwADAP7/C,则在执行此代码后,/tmp/file.dec包含完全相同的字符串...

有人知道为什么它没有被解码吗?

1 个答案:

答案 0 :(得分:2)

你正在阅读错误的信息流。此

while ((count = is.read(buff)) > 0)

应该是

while ((count = b64is.read(buff)) > 0)