使用 Java 邮件保存附件时如何加快时间?
How to speed up time when using Java Mail to save attachments?
我把Message msg分成Multipart multi1 = (Multipart) msg.getContent()。
邮件附件在一个 BodyPart 中,Part part = multi1.getBodyPart(i);
那我要保存附件。
private void saveFile(String fileName, InputStream in) throws IOException {
File file = new File(fileName);
if (!file.exists()) {
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
in = new BufferedInputStream(in);
byte[] buf = new byte[BUFFSIZE];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (FileNotFoundException e) {
LOG.error(e.toString());
} finally {
// close streams
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
但是读取IO Stream花费了太多时间。例如,一个 2.7M 的文件需要将近 160 秒才能保存在磁盘上。我已经尝试过 Channel 和其他一些 IO Stream,但没有任何改变。使用 Java 邮件保存附件的任何解决方案?
此操作有两个关键部分 - 从邮件服务器读取数据并将数据写入文件系统。很可能是服务器的速度和与服务器的网络连接控制着操作的整体速度。您可以尝试设置 mail.imap.fetchsize and mail.imap.partialfetch 属性以查看是否可以提高性能。
您也可以尝试使用 NullOutputStream 之类的东西而不是 FileOutputStream 来仅测量读取数据的速度。
其实mail.imaps.partialfetch生效了,速度也快了很多。我之前的代码有错误。
props.put("mail.imap.partialfetch","false");
props.put("mail.imap.fetchsize", "1048576");
props.put("mail.imaps.partialfetch", "false");
props.put("mail.imaps.fetchsize", "1048576");
而不是
props.put("mail.imap.partialfetch",false);
props.put("mail.imap.fetchsize", "1048576");
props.put("mail.imaps.partialfetch", false);
props.put("mail.imaps.fetchsize", "1048576");
在"false"上加引号很重要。否则参数不生效
无论如何,感谢 Bill Shannon。
我把Message msg分成Multipart multi1 = (Multipart) msg.getContent()。 邮件附件在一个 BodyPart 中,Part part = multi1.getBodyPart(i); 那我要保存附件。
private void saveFile(String fileName, InputStream in) throws IOException {
File file = new File(fileName);
if (!file.exists()) {
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
in = new BufferedInputStream(in);
byte[] buf = new byte[BUFFSIZE];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (FileNotFoundException e) {
LOG.error(e.toString());
} finally {
// close streams
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
但是读取IO Stream花费了太多时间。例如,一个 2.7M 的文件需要将近 160 秒才能保存在磁盘上。我已经尝试过 Channel 和其他一些 IO Stream,但没有任何改变。使用 Java 邮件保存附件的任何解决方案?
此操作有两个关键部分 - 从邮件服务器读取数据并将数据写入文件系统。很可能是服务器的速度和与服务器的网络连接控制着操作的整体速度。您可以尝试设置 mail.imap.fetchsize and mail.imap.partialfetch 属性以查看是否可以提高性能。
您也可以尝试使用 NullOutputStream 之类的东西而不是 FileOutputStream 来仅测量读取数据的速度。
其实mail.imaps.partialfetch生效了,速度也快了很多。我之前的代码有错误。
props.put("mail.imap.partialfetch","false");
props.put("mail.imap.fetchsize", "1048576");
props.put("mail.imaps.partialfetch", "false");
props.put("mail.imaps.fetchsize", "1048576");
而不是
props.put("mail.imap.partialfetch",false);
props.put("mail.imap.fetchsize", "1048576");
props.put("mail.imaps.partialfetch", false);
props.put("mail.imaps.fetchsize", "1048576");
在"false"上加引号很重要。否则参数不生效
无论如何,感谢 Bill Shannon。