2011-09-07 19 views
0

SFTP 서버에서 2 파일을 다운로드하고 타임 스탬프 이름을 압축하여 내 로컬 서버에 저장해야하는 프로젝트에서 작업하고 있습니다. 또한 파일이 검색되면 작업을 성공적으로 완료했거나 실패했음을 알리는 전자 메일을 보내려고합니다. SFTP 서버를 검색하는 데 JSch를 사용하고 있으며 로컬 서버에 파일을 저장할 수 있습니다. 누구든지 내 코드를 작성하여 파일을 압축하고 이메일을 보내야한다고 제안 할 수 있습니까? 어떤 도움을 주셔서 감사 드리며이 작은 프로젝트를 위해 Java로 작업하고 있습니다.SFTP 서버에서 다운로드 한 파일 압축하기

답변

1

ZipOutputStreamJava Mail을 사용하면 원하는 것을 할 수 있습니다. 필자는 호스트에서 명령 행 인수로 /부터 시작하는 샘플 main 메소드를 작성했습니다. 이미 압축 파일 이름을 알고 있다고 가정하고 우편 번호가 첨부 된 전자 메일을 보냅니다. 이게 도움이 되길 바란다!

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(); 
    } 
    } 
} 
관련 문제