2014-10-10 99 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块中。对不起浪费任何人的时间。