2014-02-19 72 views
1

我使用JSCH將文件上傳到SFTP。它可以正常工作,但有時會在文件上傳時關閉TCP連接,從而導致服務器上的截斷文件。如何重寫JSCH SFTP?

我發現SFTP服務器上的reput命令恢復上傳。我如何用JSCH發送重新命令?甚至有可能嗎?

這裏是我的代碼:

public void upload(File file) throws Exception 
{ 
    JSch jsch = new JSch(); 

    Session session = jsch.getSession(USER, HOST, PORT); 

    session.setPassword(PASSWORD); 

    java.util.Properties config = new java.util.Properties(); 
    config.put("StrictHostKeyChecking", "no"); 
    session.setConfig(config); 

    session.connect(); 

    Channel channel=session.openChannel("sftp"); 
    channel.connect(); 
    ChannelSftp sftpChannel = (ChannelSftp)channel; 


    sftpChannel.put(file.getAbsolutePath(), file.getName()); 

    channel.disconnect(); 
    session.disconnect(); 
} 

回答

2

我找到了一種方法。與RESUME參數使用 「放」 的方法:

sftpChannel.put(file.getAbsolutePath(), file.getName(), ChannelSftp.RESUME); 

我的代碼變成了:

public static void upload(File file, boolean retry) { 
    try 
    { 
     System.out.println("Uplodaing file " + file.getName()); 

     JSch jsch = new JSch(); 
     Session session = jsch.getSession(USER, HOST, PORT); 
     session.setPassword(PASSWORD); 

     java.util.Properties config = new java.util.Properties(); 
     config.put("StrictHostKeyChecking", "no"); 
     session.setConfig(config); 

     session.connect(); 

     Channel channel = session.openChannel("sftp"); 
     channel.connect(); 
     ChannelSftp sftpChannel = (ChannelSftp) channel; 

     if (!retry) 
      sftpChannel.put(file.getAbsolutePath(), file.getName(), ChannelSftp.OVERWRITE); 
     else 
      sftpChannel.put(file.getAbsolutePath(), file.getName(), ChannelSftp.RESUME); 

     channel.disconnect(); 
     session.disconnect(); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
     upload(file, true); 
    } 

}