压缩从SFTP服务器下载的文件

时间:2011-09-07 21:24:44

标签: java email zip

我正在开发一个项目,我需要从SFTP服务器下载2个文件,用时间戳名称将其压缩并保存到我的本地服务器。此外,一旦检索到文件,我希望它发送一封电子邮件,表明它已成功完成作业或失败。我使用JSch来检索SFTP服务器,并可以将文件保存在我的本地服务器中。任何人都可以建议我应该如何编写我的代码来压缩文件并发送电子邮件。任何帮助表示赞赏,我正在使用Java来完成这个小项目。

1 个答案:

答案 0 :(得分:1)

使用ZipOutputStreamJava Mail,你应该能够做你想做的事。我创建了一个示例main方法,它接收主机,from和to作为命令行参数。它假设您已经知道压缩文件名并发送附带zip的电子邮件。我希望这有帮助!

public class ZipAndEmail {
  public static void main(String args[]) {
    String host = args[0];
    String from = args[1];
    String to = args[2];

    //Assuming you already have this list of file names
    String[] filenames = new String[]{"filename1", "filename2"};

    try {
      byte[] buf = new byte[1024];
      String zipFilename = "outfile.zip";
      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilename));

      for (int i=0; i<filenames.length; i++) {
        FileInputStream in = new FileInputStream(filenames[i]);
        out.putNextEntry(new ZipEntry(filenames[i]));
        int len;
        while ((len = in.read(buf)) > 0) {
          out.write(buf, 0, len);
        }
        out.closeEntry();
        in.close();
      }
      out.close();


      Properties props = System.getProperties();
      props.put("mail.smtp.host", host);
      Session session = Session.getDefaultInstance(props, null);

      // Define message
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject("Your Zip File is Attached");

      MimeBodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText("Your zip file is attached");
      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);

      // Part two is attachment
      messageBodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource(zipFilename);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(zipFilename);
      multipart.addBodyPart(messageBodyPart);

      // Put parts in message
      message.setContent(multipart);

      // Send the message
      Transport.send( message );

      // Finally delete the zip file
      File f = new File(zipFilename);
      f.delete();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}