2014-10-10 104 views
1

這是我使用通過SFTP發送文件的代碼:Zip文件(排序)後,SFTP轉移/把(Jsch)

private void send (String sftpHost, int sftpPort, String user, String sshPrivateKeyPath, String sshPassphrase, String sftpDir, String fileName) { 
    Session session = null; 
    Channel channel = null; 
    ChannelSftp channelSftp = null; 
    FileInputStream fis = null; 
    try { 
     JSch jsch = new JSch(); 
     jsch.addIdentity(sshPrivateKeyPath, sshPassphrase); 
     java.util.Properties config = new java.util.Properties(); 
     config.put("StrictHostKeyChecking", "no"); 
     session.setConfig(config); 
     session.connect(); 
     channel = session.openChannel("sftp"); 
     channel.connect(); 
     channelSftp = (ChannelSftp) channel; 
     channelSftp.cd(sftpDir); 
     File f = new File(fileName); 
     fis = new FileInputStream(f); 
     channelSftp.put(fis, f.getName(), ChannelSftp.OVERWRITE); 
    } catch (Exception ex) { 
     logger.error("sending file failed", ex); 
     throw new RuntimeException(ex); 
    } 
    finally{ 
     try { 
      if(fis != null) fis.close(); 
     } catch (IOException e) { 
      logger.error("Error closing stream", e); 
     } 
     if(channelSftp != null) channelSftp.exit(); 
     if(channel != null) channel.disconnect(); 
     if(session != null) session.disconnect(); 
    } 
} 

兩款機器的CentOS 6.5虛擬機,JAVA 1.7.0_51, OpenJDK,tomcat 7.0.50

該zip在源/客戶端服務器上使用unzip -Z工作。在目標/服務器,我得到這個錯誤:

Archive: filename.zip 
[filename.zip] 
    End-of-central-directory signature not found. Either this file is not 
    a zipfile, or it constitutes one disk of a multi-part archive. In the 
    latter case the central directory and zipfile comment will be found on 
    the last disk(s) of this archive. 
zipinfo: cannot find zipfile directory in one of filename.zip or 
      filename.zip.zip, and cannot find filename.zip.ZIP, period. 

的文件大小也發生變化:

源(OK)

-rw-r--r--. 1 root root 49170 Oct 10 15:35 filename.zip 

Detination(損壞)

-rw-rw-r--. 1 user user 45710 Oct 10 15:35 filename.zip 

我也嘗試在損壞的文件上運行jar -tf並得到:

java.util.zip.ZipException: error in opening zip file 

但是當我嘗試jar xvf時,它成功地提取了這些文件。所以它不完全「損壞」

我也嘗試通過WinSCP傳輸到我的Windows 7機器,並嘗試7zip,但它也無法打開文件。

我在想也許Jsch有一個二進制文件的設置,但我還沒有找到任何。

感謝您的幫助/方向,你可以給

更新1:我也試過Jsch的SCP接口相同的結果

更新2:我已經試過sshj SFTP具有相同的結果。所以不是一個jsch問題...

更新3:我也嘗試添加下面的代碼。雖然文件大小發生了變化,但仍然無法打開並解壓縮-Z

config.put("compression.s2c", "none"); 
config.put("compression.c2s", "none"); 
config.put("compression_level", "0"); 
+0

這是[ZIP規格](http://www.pkware.com/documents/casestudies/APPNOTE.TXT)。這聽起來像文件已被截斷。比較傳輸前後的長度。 – 2014-10-10 16:18:35

+0

謝謝,它爲什麼會截斷? – patlv23 2014-10-10 16:57:03

+0

不知道 - 我從來沒有聽說過截斷數據的文件傳輸(至少從星期二開始)。 – 2014-10-10 17:32:26

回答

0

這一切都是由我的愚蠢造成的。用於創建此代碼所使用的zip的zipout並未關閉,即zip創建和文件發送位於同一個try-catch-finally塊中。對不起浪費任何人的時間。