JAVA Ftpclent将一个FTP中的文件直接上传到另一个FTP,
支持多文件。
修改多文件时,输出流第二次为空问题
解决Docker环境中storeFileStream 为空的问题.
由于是片段代码,大家拿去时考虑异常处理。有问题可以留言咨询。
import org.apache.hadoop.hbase.shaded.org.apache.commons.net.ftp.FTPClient;
public class FtpUtil {
public static String readConfigfileForFTP() throws SocketException,IOException {
FTPClient ftpRemote = new FTPClient();
FTPClient ftpLocal = new FTPClient();
ftpRemote.connect(ftphost, ftpport);
//连接ftpRemote
boolean isloginOne = ftpRemote.login(ftpusername, ftppassword);
if (!FTPReply.isPositiveCompletion(ftpRemote.getReplyCode())) {
logger.info("连接失败,用户名或密码错误");
} else {
logger.info("FTP连接成功");
}
if (isloginOne ) {
ftpRemote.enterLocalPassiveMode();
logger.info("获取ftpRemote路径" + ftpath + "文件");
// 获取ftpRemote目录下的文件
FTPFile[] ftp = ftpRemote.listFiles(ftpath);
for (FTPFile file : ftp) {
//多次文件每次需要等陆ftp,登出ftp。否则 文件输入流会为空
ftpLocal.connect(ftphostbf, ftpportbf);
//连接ftpLocal
boolean isloginTwo = ftpLocal.login(ftpusernamebf, ftppasswordbf);
if (!FTPReply.isPositiveCompletion(ftpRemote.getReplyCode())) {
logger.info("连接失败,用户名或密码错误");
} else {
logger.info("备份FTP连接成功");
}
String st = new String(file.getName().getBytes(), "UTF-8");
logger.info("开始备份"+st+"文书");
if (st.endsWith("zip")) {
logger.info(ftpname + "开始时间");
//ftpLocal.setRemoteVerificationEnabled(false);
//docker中需要将设置被动模式,否则 输出流会为空。
ftpLocal.enterLocalPassiveMode(); //设置被动模式(FTP客户端在docker容器内
// 获取ftpLocal输出流
OutputStream is = ftpLocal.storeFileStream(ftpLocal.printWorkingDirectory()+ localFile+ "/"+ file.getName());
if (is == null) {
logger.error("目标文件不存在");
}
ftpRemote.changeWorkingDirectory(ftpath);
ftpRemote.setFileType(FTP.BINARY_FILE_TYPE);
// 通过流把FTPOne复制到FTPTwo
ftpRemote.retrieveFile(file.getName(), is);
logger.info(st + "备份完成");
is.close();
// 检查返回值是否成功
ftpLocal.completePendingCommand();
logger.info(ftpname + "结束时间");
}
//ftp退出登录
ftpLocal.logout();//
}
}
ftpRemote.logout();
if (ftpRemote.isConnected()) {
ftpRemote.disconnect();
}
if (ftpLocal.isConnected()) {
ftpLocal.disconnect();
} else {
logger.error("ftp路径错误");
}
return "数据全部已完成";
}
}
参考:https://blog.youkuaiyun.com/weixin_42158424/article/details/90643422