可以使用 Apache Commons Net 库中的 FTPClient 类来实现 FTP 文件传输功能。

以下是实现该功能的 Java 代码示例:

import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

public class FTPUtil {
    private FTPClient ftpClient;

    public FTPUtil() {
        ftpClient = new FTPClient();
    }

    public void connect(String hostname, int port, String username, String password) throws IOException {
        ftpClient.connect(hostname, port);
        ftpClient.login(username, password);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    }

    public void downloadDirectory(String directoryPath, String destinationPath) throws IOException {
        ftpClient.changeWorkingDirectory(directoryPath);
        String[] files = ftpClient.listNames();
        for (String file : files) {
            String filePath = directoryPath + '/' + file;
            if (ftpClient.getFileType() == FTP.BINARY_FILE_TYPE) {
                downloadFile(filePath, destinationPath);
            }
        }
    }

    private void downloadFile(String filePath, String destinationPath) throws IOException {
        InputStream inputStream = ftpClient.retrieveFileStream(filePath);
        FileOutputStream outputStream = new FileOutputStream(destinationPath + '/' + new File(filePath).getName());
        byte[] bytesArray = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(bytesArray)) != -1) {
            outputStream.write(bytesArray, 0, bytesRead);
        }
        boolean success = ftpClient.completePendingCommand();
        if (!success) {
            throw new IOException('Failed to download file: ' + filePath);
        }
        outputStream.close();
        inputStream.close();
    }

    public void disconnect() throws IOException {
        if (ftpClient.isConnected()) {
            ftpClient.logout();
            ftpClient.disconnect();
        }
    }
}

// 使用示例
public static void main(String[] args) {
    FTPUtil ftpUtil = new FTPUtil();
    try {
        ftpUtil.connect('ftp.example.com', 21, 'ftp-user1', 'password');
        ftpUtil.downloadDirectory('/home/vsftpd/ftp-user1/old', '/home/vsftpd/ftp-user1/new');
        ftpUtil.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

该代码首先创建了一个FTPUtil类,该类封装了FTPClient对象,实现了 FTP 连接、下载文件、断开连接等功能。

main方法中创建FTPUtil对象并连接到 FTP 服务器,然后调用downloadDirectory方法下载指定目录下的所有文件到本地目录。最后断开与 FTP 服务器的连接。

注意,该代码中使用了FTP.BINARY_FILE_TYPE指定了文件传输类型为二进制类型,可以确保在不同操作系统之间传输文件时不会出现格式问题。如果需要传输文本文件,应该使用FTP.ASCII_FILE_TYPE类型。

Java 使用 FTP 客户端将服务器文件复制到另一个目录

原文地址: https://www.cveoy.top/t/topic/oxq4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录