public static void uploadFileToSFTP(String host, int port, String username,
String password,String directory, String uploadFile,String newFileName)
throws Exception {
Session sshSession =null;
Channel channel =null;
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect(5000);
channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
try {
sftp.cd(directory);
}catch(SftpException ex){
ATTACH_SERVICE_LOG.error("FTP服务器[{}]上目录[{}]可能不存在,需要创建!",host,directory);
String[] dirs = directory.split("/");
String tempPath = "";
for (String dir : dirs) {
if (null == dir || "".equals(dir))
continue;
tempPath+="/"+dir;
try {
ATTACH_SERVICE_LOG.error("检测目录[" + tempPath + "]");
sftp.cd(tempPath);
} catch (SftpException ex1) {
try {
ATTACH_SERVICE_LOG.error("创建目录[" + tempPath + "]");
sftp.mkdir(tempPath);
sftp.cd(tempPath);
ATTACH_SERVICE_LOG.error("进入目录[" + tempPath + "]");
} catch (SftpException e1) {
ATTACH_SERVICE_LOG.error("创建目录[" + tempPath
+ "]失败1,异常信息[" + e1.getMessage() + "]");
throw new Exception("创建目录[" + tempPath
+ "]失败1,异常信息[" + e1.getMessage() + "]");
}
}
}
}
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), newFileName);
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally{
if (sftp !=null){
sftp.exit();
sftp.disconnect();
}
if (channel !=null){
channel.disconnect();
}
if (sshSession !=null){
sshSession.disconnect();
}
}
}
public static void downloadSFTPFile(String host, int port, String username,String password,
String directory, String downloadFile,String saveFile)
throws Exception {
Session sshSession =null;
Channel channel =null;
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
System.out.println("Session created.");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println("Session connected.");
System.out.println("Opening Channel.");
channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("Connected to " + host + ".");
sftp.cd(directory);
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally{
if (sftp !=null){
sftp.exit();
sftp.disconnect();
}
if (channel !=null){
channel.disconnect();
}
if (sshSession !=null){
sshSession.disconnect();
}
}
}