ftp上传文件及将文件上传到指定目录下(多层目录下)

本文介绍了一个Java实现的FTPUtil1类,该类能够连接FTP服务器并上传文件到指定的多层目录下。通过创建FTPClient实例,设置被动模式,然后递归创建远程目录结构,确保目标路径存在,最后将本地文件以二进制模式存储到FTP服务器。示例代码展示了如何使用该类上传单个文件和整个目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.xjg.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;


import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;


public class FtpUtil1 {
private FTPClient ftp;


    /**
    * FTPClient构造函数,主要进行初始化配置连接FTP服务器。
    * 
    * @param host
    *            FTP服务器的IP地址
    * @param port
    *            FTP服务器的端口
    * @param userName
    *            FTP服务器的用户名
    * @param passWord
    *            FTP服务器的密码
    */
    public FtpUtil1(String host, int port, String userName, String passWord) {
        ftp = new FTPClient();
        try {
            ftp.connect(host, port);// 连接FTP服务器
            ftp.login(userName, passWord);// 登陆FTP服务器
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                System.out.println("未连接到FTP,用户名或密码错误。");
                ftp.disconnect();
            } else {
                System.out.println("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            System.out.println("FTP的IP地址可能错误,请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("FTP的端口错误,请正确配置。");
        }
    }


    /**
    * 上传文件到FTP服务器
    * 
    * @param local
    *            本地文件名称,绝对路径
    * @param remote
    *            远程文件路径,支持多级目录嵌套,支持递归创建不存在的目录结构
    * @throws IOException
    */
    public void upload(String local, String remote) throws IOException {
        // 设置PassiveMode传输
        ftp.enterLocalPassiveMode();
        // 设置以二进制流的方式传输
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        // 对远程目录的处理
        String remoteFileName = remote;
        if (remote.contains("/")) {
            remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
            // 创建服务器远程目录结构,创建失败直接返回
            if (!CreateDirecroty(remote)) {
                return;
            }
        }
        FTPFile[] files = ftp.listFiles(new String(remoteFileName));
        File f = new File(local);
        uploadFile(remoteFileName, f);
    }


    public void uploadFile(String remoteFile, File localFile)
            throws IOException {
        InputStream in = new FileInputStream(localFile);
        ftp.storeFile(remoteFile, in);
        in.close();
    }


    /** */
    /**
    * 递归创建远程服务器目录
    * 
    * @param remote
    *            远程服务器文件绝对路径
    * 
    * @return 目录创建是否成功
    * @throws IOException
    */
    public boolean CreateDirecroty(String remote) throws IOException {
        boolean success = true;
        String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
        // 如果远程目录不存在,则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase("/")
                && !ftp.changeWorkingDirectory(new String(directory))) {int start = 0;
                int end = 0;
                if (directory.startsWith("/")) {
                    start = 1;
                } else {
                    start = 0;
                }
                end = directory.indexOf("/", start);
                while (true) {
                    String subDirectory = new String(remote.substring(start, end));
                    if (!ftp.changeWorkingDirectory(subDirectory)) {
                        if (ftp.makeDirectory(subDirectory)) {
                            ftp.changeWorkingDirectory(subDirectory);
                        } else {
                            System.out.println("创建目录失败");
                            success = false;
                            return success;
                        }
                    }
                    start = end + 1;
                    end = directory.indexOf("/", start);
                    // 检查所有目录是否创建完毕
                    if (end <= start) {
                        break;
                    }
                }
            }
            return success;
        }


        public boolean uploadAll(String filename, String uploadpath)
                throws Exception {
            boolean success = false;
            File file = new File(filename);
            // 要上传的是否存在
            if (!file.exists()) {
                return success;
            }
            // 要上传的是否是文件夹
            if (!file.isDirectory()) {
                return success;
            }
            File[] flles = file.listFiles();
            for (File files : flles) {
                if (files.exists()) {
                    if (files.isDirectory()) {
                        this.uploadAll(files.getAbsoluteFile().toString(),
                                uploadpath);
                    } else {
                        String local = files.getCanonicalPath().replaceAll("\\\\",
                                "/");
                        String remote = uploadpath
                                + local.substring(local.indexOf("/") + 1);
                        upload(local, remote);
                        ftp.changeWorkingDirectory("/");
                    }
                }
            }
            return true;
        }


        public static void main(String[] args) throws Exception {
//             FileInputStream in = new FileInputStream(new File("E:/1.jpg"));
            FtpUtil1 ftp = new FtpUtil1("192.168.25.119", 21, "apk_updata", "bef3xcyktlle67BL");
            String name="app-release.apk";//文件名
            String pathName="/aa/bb/"+name;//文件存放路径加文件名
             ftp.upload("E:/app-release1.apk", pathName);//上传
//            ftp.uploadAll("E:/1.txt", "/bb/aa/");
//             ftp.CreateDirecroty("/bb/cc/");
        }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值