从MimeMultipart解码Base64内容

时间:2011-06-24 13:57:27

标签: java base64 mime javamail

我在我的MimeMessage的一部分中有一个Base64文件。 我这样说了

DataSource source = new FileDataSource(new File("base64Test.bin"));
bodyPart.setDataHandler(new DataHandler(source));

然后,我想使用方法BASE64DecoderStream.decode

对其进行解码
String base64 = (String)bodyPart.getContent();
byte [] base64Decoder = BASE64DecoderStream.decode(base64.getBytes());

问题在于,当我使用这种方法时,我总是ArrayOutOfboundexception

为解决这个问题有什么建议吗?

2 个答案:

答案 0 :(得分:1)

据我所知,Base64DecoderStream采用的是InputStream,而不是字节数组。至少,您需要像这样更改解码:

ByteArrayInputStream contentStream = new ByteArrayInputStream(base64Content.getBytes());
BASE64DecoderStream decodeStream = new BASE64DecoderStream(contentStream);
int decodedByte
while ((decodedByte = read()) != -1) {
   // handled decoded bytes
}

也许autoboxing正试图帮助你,而一些“中间”数组创建正在污染这些作品。或者,也许您的消息足够大,无法创建足够大的数组。或者你可能有两个线程调用静态产品,这会搞乱内部共享缓冲区。

答案 1 :(得分:1)

我像这样阅读BASE64DecoderStream:

DataHandler handler = bodyPart.getDataHandler(); System.out.println(“attachment name:”+ handler.getName());

FileOutputStream fos = new FileOutputStream(new File(handler.getName())); handler.writeTo(FOS);

此OutPutStream正在写入已写入文件的数据。