gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:44:34 27 4
gpt4 key购买 nike

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

最佳答案

使用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();
}
}
}

关于java - 压缩从 SFTP 服务器下载的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7340696/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com