java 通过ftp 将服务器上homevsftpdftp-user1old的所有文件复制到homevsftpdftp-user1new目录中
可以使用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/gHsF 著作权归作者所有。请勿转载和采集!