使用Java Mail保存附件时如何加快时间?

Cai*_*ain 1 io performance jakarta-mail

我将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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是在读取IO Stream上花费了太多时间。例如,一个2.7M文件需要将近160秒才能保存到磁盘上。我已经尝试过Channel和其他一些IO Stream,但是没有任何改变。使用Java Mail保存附件的任何解决方案?

有关更多代码信息,请访问https://github.com/cainzhong/java-mail-demo/blob/master/src/main/java/com/java/mail/impl/ReceiveMailImpl.java

Cai*_*ain 5

实际上,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"); 
Run Code Online (Sandbox Code Playgroud)

代替

props.put("mail.imap.partialfetch",false);
props.put("mail.imap.fetchsize", "1048576"); 
props.put("mail.imaps.partialfetch", false); 
props.put("mail.imaps.fetchsize", "1048576"); 
Run Code Online (Sandbox Code Playgroud)

在“ false”上加上引号很重要。否则,参数将不会生效。

无论如何,多亏了比尔·香农。