用戶需求:將一臺ftp服務器上的文件轉移到另一臺ftp服務器,ftp服務器都採用sftp連接。
解決方案:1.首先從第一臺ftp服務器下載文件到本地,再從本地上傳到另一臺ftp服務器
2.直接獲取第一臺ftp服務器的文件字節流寫入到第二臺ftp服務器
由於第一種方案還需要持久化到本地,步驟有些多餘,我這裏直接選用第二種方案。要求都是sftp連接,因此引入jsch的jar包,如果是ftp連接可以用sun和Apache的FTPClient(sun的FTPClient在jdk1.6後不支持)
代碼實現:
1.sftp連接
JSch jsch = new JSch();
try {
session = jsch.getSession(username, url, port);
System.out.println("Session created for " + url);
session.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.connect();
System.out.println("Session connected to " + url);
channel = session.openChannel("sftp");
channel.connect();
System.out.println("Opening Channel for " + url);
sftp = (ChannelSftp) channel;
} catch (JSchException e) {
e.printStackTrace();
}
2.文件傳輸
InputStream is = null;
try {
is = fromSftp.get(fromPath);
// 創建目標目錄
createDir(toPath, toSftp);
toSftp.put(is, fileName);
// 創建備份目錄,將傳輸過的文件備份
createDir(backupPath, fromSftp);
fromSftp.rename(fromPath, backupPath + fileName);
System.out.println(fileName + " rename to " + backupPath);
} catch (SftpException e) {
e.printStackTrace();
} finally {
try {
if(null != is){
// 關閉流
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
3.關閉session、channel、channelsftp
session.disconnect();
channel.disconnect();
sftp.quit();
sftp.disconnect();