我正在使用Javamail API,并且正在尝试下载附件文件,例如一个单词文件。 问题是,当我尝试读取字节并将其保存到文件时,出现base64解码异常。 我为此使用了下面的代码。正在下载单词使用Javamail的Gmail文档
堆栈异常:
IOException:com.sun.mail.util.DecodingException: BASE64Decoder: Error in encoded stream: needed 4 valid base64 characters but only got 2 before EOF, the 10 most recent characters were: "AG4AAAAAAA"
JavaMail的代码:
private void getAttachments(Message temp) throws IOException, MessagingException {
List<File> attachments = new ArrayList<File>();
Multipart multipart = (Multipart) temp.getContent();
System.out.println(multipart.getCount());
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
continue; // dealing with attachments only
}
InputStream is = bodyPart.getInputStream();
File f = new File("C:\\Attachments\\" + bodyPart.getFileName());
// saveFile(bodyPart.getFileName(),is);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (br.ready()) {
System.out.println(br.readLine());
}
saveFile(bodyPart.getFileName(),is);
attachments.add(f);
}
public static void saveFile(String filename,InputStream input)
{
System.out.println(filename);
try {
if (filename == null) {
//filename = File.createTempFile("VSX", ".out").getName();
return;
}
// Do no overwrite existing file
filename = "C:\\Attachments\\" + filename;
File file = new File(filename);
for (int i = 0; file.exists(); i++) {
file = new File(filename + i);
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(input);
int aByte;
while ((aByte = bis.read()) >=0) {
bos.write(aByte);
}
bos.flush();
bos.close();
bis.close();
} // end of try()
catch (IOException exp) {
System.out.println("IOException:" + exp);
}
} //end of saveFile()
您发布的代码看起来不错。所以可能你的问题在于JavaMail特定的代码。你能告诉我们该代码,以及异常的消息和堆栈跟踪吗? –
@RolandIllig 我再次编辑了代码 –
当您直接从MimeBodyPart中调用saveFile()方法而不是滚动自己的保存逻辑时会发生什么? –