我有使用java邮件下载阿拉伯文附件的问题.
文件名始终不明确.
问题是将Bodypart附件检索为非UTF-8字符.
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();
// getFilename always have wrong characters set
byte [] fileBytes = bodyPart.getFileName().toString().getBytes();
String filename = new String(fileBytes, "UTF-8");
File f = new File("C:\\Attachments\\" + filename);
System.out.println(f .getName());
try {
if (f == null) {
//filename = File.createTempFile("VSX", ".out").getName();
return;
}
FileOutputStream fos = new FileOutputStream(f );
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(is);
int aByte;
while ((aByte = bis.read()) >=0) {
bos.write(aByte);
}
fos.flush();
bos.flush();
bos.close();
bis.close();
fos.close();
} // end of try()
catch (IOException exp) {
System.out.println("IOException:" + exp);
}
attachments.add(f);
}
}
Run Code Online (Sandbox Code Playgroud)
头部根据RFC 2047(它的encoded-word)中描述的机制进行编码,该机制表示匹配=?<encoding> ?B?<encoded-bytes>的头部分?=是字节编码部分.所述<编码>说如何解释的字节数,和(因为它是B风格,而不是Q样式)的<编码字节>是base-64编码.
这一切都相当复杂.幸运的是,您可以使用静态javax.mail.internet.MimeUtility.decodeText()方法轻松处理此问题.这意味着您可以切换到:
String filename = MimeUtility.decodeText(bodyPart.getFileName());
Run Code Online (Sandbox Code Playgroud)
实际上,你最好将它与下一行结合起来:
File f = new File("C:\\Attachments",
MimeUtility.decodeText(bodyPart.getFileName()));
Run Code Online (Sandbox Code Playgroud)
它更好,因为它避免了构建文件名的麻烦,而不是手动完成所有操作.(这也意味着您可以将该文字路径名分解为某个配置位置.)
| 归档时间: |
|
| 查看次数: |
2719 次 |
| 最近记录: |