Java 使用 FTP 复制文件:将服务器文件从一个目录复制到另一个目录
可以使用 Apache Commons Net 库来实现 Java 通过 FTP 复制文件的操作。以下是实现该操作的示例代码:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class CopyFtpFiles {
public static void main(String[] args) {
String server = 'ftp.example.com';
int port = 21;
String username = 'ftp-user1';
String password = 'password';
String oldDir = '/home/vsftpd/ftp-user1/old';
String newDir = '/home/vsftpd/ftp-user1/new';
FTPClient ftpClient = new FTPClient();
try {
// 连接 FTP 服务器
ftpClient.connect(server, port);
ftpClient.login(username, password);
// 设置文件传输模式为二进制
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// 获取 old 目录下的所有文件
FTPFile[] files = ftpClient.listFiles(oldDir);
// 遍历 old 目录下的所有文件
for (FTPFile file : files) {
String fileName = file.getName();
String filePath = oldDir + '/' + fileName;
// 下载文件到本地
InputStream inputStream = ftpClient.retrieveFileStream(filePath);
OutputStream outputStream = ftpClient.storeFileStream(newDir + '/' + fileName);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
inputStream.close();
outputStream.close();
// 判断文件是否下载成功
boolean success = ftpClient.completePendingCommand();
if (success) {
System.out.println(fileName + ' 下载成功');
} else {
System.out.println(fileName + ' 下载失败');
}
}
// 断开 FTP 连接
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
请注意,需要确保服务器上的 FTP 用户具有在 old 目录中读取文件和在 new 目录中写入文件的权限。
原文地址: https://www.cveoy.top/t/topic/oxrn 著作权归作者所有。请勿转载和采集!