private static final String FTP_SERVER = "";
private static final int FTP_PORT = ;
private static final String USER_NAME = "";
private static final String PASSWORD = "";
public static void main(String[] args) {
FTPSClient ftpClient = new FTPSClient();
try {
// 连接到FTP服务器
ftpClient.connect(FTP_SERVER, FTP_PORT);
int replyCode = ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(replyCode)){
System.out.println(replyCode);
return;
}
//ftpClient.execPBSZ(0);
//ftpClient.execPROT("P");
boolean loginSuccess = ftpClient.login(USER_NAME, PASSWORD);
if (!loginSuccess) {
System.out.println("Login failed.");
return;
}
//ftpClient.addProtocolCommandListener(new PrintCommandListener(System.out));
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
ftpsClient.execPBSZ(0); // 设置私钥大小为 0 表示使用默认值
ftpsClient.execPROT("P"); // 设置数据通道加密模式
ftpClient.setControlEncoding("UTF-8");
ftpClient.setBufferSize(1024);
// 设置被动模式
ftpClient.enterLocalPassiveMode();
ftpClient.setRemoteVerificationEnabled(false);
// 设置二进制传输模式
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.setDefaultTimeout(30000);
// 源目录和目标目录
String sourceDirectory = "/IT-ceshi/trans_report/WX123/M000101_AR00022";
String targetDirectory = "/IT-ceshi/trans_report_to/WX123/M000101_AR00022";
// 复制目录中的所有文件
copyDirectoryFiles(ftpClient, sourceDirectory, targetDirectory);
// 断开连接
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void copyDirectoryFiles(FTPSClient client, String sourceDir, String targetDir) throws IOException {
// 获取源目录的文件列表
//client.changeWorkingDirectory(sourceDir);
FTPFile[] ftpFiles = client.listFiles(sourceDir);
String localFilePath ="D:\\csm";
// 遍历文件列表
for (FTPFile file : Arrays.asList(ftpFiles)) {
String sourcePath = sourceDir + "/" + file.getName();
String lPath = localFilePath + "\\" + file.getName();
FileOutputStream fos = new FileOutputStream(lPath);
// 下载文件
boolean downloadSuccess = client.retrieveFile(sourcePath, fos);
fos.close();
}
// 切换到目标目录
boolean changedToTargetDir = client.changeWorkingDirectory(targetDir);
if (!changedToTargetDir) {
// 如果目标目录不存在,则创建
boolean createdTargetDir = client.makeDirectory(targetDir);
if (createdTargetDir) {
// 切换到新创建的目标目录
client.changeWorkingDirectory(targetDir);
} else {
throw new IOException("Failed to create target directory: " + targetDir);
}
}
for (FTPFile file : Arrays.asList(ftpFiles)) {
String targetPath = targetDir + "/" + file.getName();
String lPath = localFilePath + "\\" + file.getName();
FileInputStream fis = new FileInputStream(new File(lPath));
boolean uploadSuccess = client.storeFile(targetPath, fis);
fis.close();
}
}
FTP 复制文件夹
最新推荐文章于 2024-08-18 23:25:39 发布