Base64-encode a file and compress it

ⅰ亾dé卋堺 提交于 2019-12-05 09:49:40
DRCB

BASE64 encoded data are usually longer than source, however you are using the length of the source data to write encoded to output stream.

You have use size of the generated array instead of your variable len.

Second notice - do not redefine buffer each time you encode a byte. Just write result into output.

 while ((len = in.read(buffer)) > 0)  {                         
     byte [] enc = Base64.encodeBase64(Arrays.copyOf(buffer, len));
     out.write(enc, 0, enc.length);
 }

UPDATE: Use Arrays.copyOf(...) to set length of the input buffer for encoding.

Your main problem is that base64 encoding can not be applied block-wise (especially not the apache-commons implementation). This problem is getting worse because you don't even know how large your blocks are as this depends on the bytes read by in.read(..).

Therefore you have two alternatives:

  1. Load the complete file to memory and then apply the base64 encoding.
  2. use an alternative Base64 encoder implementation that works stream-based (the Apache Batik project seems to contain such an implementation: org.apache.batik.util.Base64EncoderStream)

When you read the file content into buffer you get len bytes. When base64 encoding this you get more than len bytes, but you still only write len bytes to the file. This beans that the last part of your read chunks will be truncated.

Also, if your read does not fill the entire buffer you should not base64 encode more than len bytes as you will otherwise get trailing 0s in the padding of the last bytes.

Combining the information above this means that you must base64 encode the whole file (read it all into a byte[]) unless you can guarantee that each chunk you read can fit exactly into a base64 encoded message. If your files are not very large I would recommend reading the whole file.

A smaller problem is that when reading in your loop you should probably check for "> -1", not "> 0", but int his case it does not make a difference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!