java实现从ftp服务器拷贝文件到另一台服务器
作者:互联网
目录
前言
通过ftp连接ftp服务器,通过sftp连接另外一台服务器,实现文件拷贝。
1、连接ftp
/**
* 连接FTP
*/
public void connect(String host, int port, String user, String pwd) {
FTPClient client = new FTPClient();
try {
// 连接
client.connect(host, port);
// 登陆
if (user == null || "".equals(user)) {
client.login("anonymous", "anonymous");
} else {
client.login(user, pwd);
}
// 二进制文件支持
client.setFileType(FTPClient.BINARY_FILE_TYPE);
// 获取FTP应答
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
client.disconnect();
return;
}
FTPClientConfig config = new FTPClientConfig(client.getSystemType().split(" ")[0]);
client.configure(config);
client.setBufferSize(1024);
client.enterLocalPassiveMode();
client.setControlEncoding("utf-8");
this.client = client;
} catch (IOException e) {
e.printStackTrace();
}
}
2、连接sftp
/**
* 连接sftp服务器
*
* @param host 主机
* @param port 端口
* @param username 用户名
* @param password 密码
*/
public void sessionConnect(String host, int port, String username, String password) {
try {
this.jsch = new JSch();
this.sshSession = jsch.getSession(username, host, port);
this.sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
this.sshSession.setConfig(sshConfig);
this.sshSession.connect();
} catch (Exception e) {
log.error("SftpUtil Session host=[" + host + "];port=[" + port + "];user=[" + username
+ "];passwd=[" + password + "] error : ", e);
}
}
/**
* 连接sftp
*/
public SftpUtils sftpConnect() {
if (sftp == null) {
try {
Channel channelSftp = this.sshSession.openChannel("sftp");
this.sftp = (ChannelSftp) channelSftp;
sftp.connect();
} catch (Exception e) {
log.error("SftpUtil ChannelSftp error : ", e.getMessage());
}
}
return this;
}
3、获取ftp文件流
/**
* 获取远程文件的输出流
*
* @param client ftp连接,这里传进来是因为不能在该方法的最后释放连接
* @param fileName 文件名称,FTP上的文件名称
* @param remotePath ftp上的远程目录文件
*/
public static InputStream retrieveFileStream(FTPClient client, String fileName, String remotePath) throws Exception {
boolean success = false;
try {
success = switchDirectory(client, remotePath, false);
if (success) {
return client.retrieveFileStream(fileName);
}
} catch (Exception e) {
log.debug("获取ftp文件流异常,error: {}", e.getMessage());
throw new RuntimeException("获取ftp文件流异常 error" + e.getMessage());
}
return null;
}
4、在sftp连接服务器上创建目录
String mkdir = "mkdir -p " + remotePath;
String exit = "exit";
sftp.shellConnect().executeShell(mkdir, exit);
/**
* 创建shell连接
*/
public SftpUtil shellConnect() {
if (shell == null) {
try {
Channel chnanelShell = this.sshSession.openChannel("shell");
shell = (ChannelShell) chnanelShell;
shell.connect();
} catch (Exception e) {
log.error("SftpUtil ChannelShell error : ", e.getMessage());
}
}
return this;
}
/**
* 执行shell 命令
*/
public boolean executeShell(String... cmds) {
ChannelShell shell = null;
try {
Channel chnanelShell = this.sshSession.openChannel("shell");
shell = (ChannelShell) chnanelShell;
shell.connect();
} catch (JSchException e) {
log.error("SftpUtil ChannelShell error : ", e);
}
try {
InputStream in = shell.getInputStream();
OutputStream out = shell.getOutputStream();
PrintWriter writer = new PrintWriter(out);
for (String cmd : cmds) {
writer.println(cmd);
}
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String msg = "";
StringBuilder result = new StringBuilder();
while ((msg = reader.readLine()) != null) {
// result.append(msg).append(System.lineSeparator());
}
} catch (IOException e) {
throw new RuntimeException("执行命令出错,cmd : " + ArrayUtils.toString(cmds) + " , error : " + e.getMessage());
} finally {
shell.disconnect();
}
return true;
}
5、上传到sftp所在服务器
/**
* 上传文件
*
* @param src 要上传的文件流
* @param dir 上传的目录
* @param fileName 文件名称
*/
public boolean uploadStream(InputStream src, String dir, String fileName) throws Exception {
boolean success = false;
try {
this.sftp.cd(dir);
this.sftp.put(src, fileName);
success = true;
} catch (Exception e) {
log.error("SftpUtil upload directory=[" + dir + "];uploadFile=[" + fileName + "] error : ", e.getMessage());
throw new RuntimeException("上传文件异常," + "upload directory=[" + dir + "];uploadFile=[" + fileName + "] error:" + e.getMessage());
} finally {
try {
if (src != null) {
src.close();
}
} catch (IOException e) {
log.error("SftpUtil upload directory=[" + dir + "];uploadFile=[" + fileName + "] close FileInputStream error : ", e);
}
}
return success;
}
标签:ftp,shell,另一台,new,sftp,client,error,服务器,String 来源: https://blog.csdn.net/RenshenLi/article/details/121411863