This is the code I use for sending a file through SFTP:
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();
}
}
Both machines are CentOS 6.5 VMs, java 1.7.0_51, OpenJDK, tomcat 7.0.50
The zip works on the source/client server with unzip -Z. On the destination/server, I get this error:
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.
The file size also is changed:
Source (ok)
-rw-r--r--. 1 root root 49170 Oct 10 15:35 filename.zip
Detination (corrupted)
-rw-rw-r--. 1 user user 45710 Oct 10 15:35 filename.zip
I also tried running jar -tf on the corrupted file and got:
java.util.zip.ZipException: error in opening zip file
But when I tried jar xvf, it successfully extracted the files. So it's not totally "corrupted"
I also tried transferring via WinSCP to my Windows 7 machine and tried 7zip, but it also couldn't open the file.
I was thinking maybe Jsch has a setting for binary files but I haven't found any.
Thanks for any help/direction you can give
UPDATE 1: I've also tried Jsch's SCP interface with the same results
UPDATE 2: I've tried sshj sftp with the same results. So not a jsch problem...
UPDATE 3: I've also tried adding the code below. Though the file size changed, it still wouldn't open with unzip -Z
config.put("compression.s2c", "none");
config.put("compression.c2s", "none");
config.put("compression_level", "0");
This was all caused by my stupidity. The zipoutstream used to create the zip used by this code was not closed yet i.e. zip creation and file sending were in the same try - catch - finally block. Sorry for wasting anybody's time.