以下是一个简单的 Java FTP 上传类,可以上传文件并自动创建远程目录:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUploader {

    private String server;
    private int port;
    private String user;
    private String password;

    public FTPUploader(String server, int port, String user, String password) {
        this.server = server;
        this.port = port;
        this.user = user;
        this.password = password;
    }

    public void uploadFile(File file, String remotePath) throws IOException {
        FTPClient ftp = new FTPClient();
        ftp.connect(server, port);
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new IOException("FTP server refused connection.");
        }
        if (!ftp.login(user, password)) {
            ftp.disconnect();
            throw new IOException("FTP login failed.");
        }
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        String[] dirs = remotePath.split("/");
        for (String dir : dirs) {
            if (!dir.isEmpty()) {
                boolean success = ftp.changeWorkingDirectory(dir);
                if (!success) {
                    if (!ftp.makeDirectory(dir)) {
                        throw new IOException("Unable to create remote directory: " + dir);
                    }
                    if (!ftp.changeWorkingDirectory(dir)) {
                        throw new IOException("Unable to change remote directory: " + dir);
                    }
                }
            }
        }
        FileInputStream fis = new FileInputStream(file);
        boolean success = ftp.storeFile(file.getName(), fis);
        fis.close();
        if (!success) {
            throw new IOException("Unable to upload file: " + file.getName());
        }
        ftp.logout();
        ftp.disconnect();
    }

    public static void main(String[] args) throws IOException {
        FTPUploader uploader = new FTPUploader("ftp.example.com", 21, "username", "password");
        File file = new File("/path/to/local/file.txt");
        String remotePath = "/path/to/remote/directory";
        uploader.uploadFile(file, remotePath);
    }

}

使用方法:

  1. 创建 FTPUploader 对象,指定 FTP 服务器地址、端口、用户名和密码。
  2. 创建要上传的文件对象,指定本地文件路径。
  3. 指定要上传到的远程目录路径。
  4. 调用 uploadFile 方法,上传文件并创建远程目录。如果远程目录已经存在,则不会重复创建,直接上传文件。

注意:该类使用了 Apache Commons Net 库中的 FTPClient 类,需要先将该库添加到项目中。可以从以下链接下载该库:

https://commons.apache.org/proper/commons-net/download_net.cgi

下载后解压缩并将其中的 commons-net-x.x.x.jar 文件添加到项目中

帮我使用 Java 创建一个 FTP 链接上传类。该类主要是用于 FTP 上传文件。如果远端多级目录不存在的话还需要创建目录再上传

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

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