ftp上传下载文件

Java FTP客户端工具类实现
package com.surfront.support.util;

import java.io.*;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by ndd on 2016/8/5.
 */
public class FtpUtil {
    private FTPClient ftp;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * @param path     上传到ftp服务器哪个路径下
     * @param addr     地址
     * @param port     端口号
     * @param username 用户名
     * @param password 密码
     * @return
     * @throws Exception
     */
    public boolean connect(String path, String addr, int port, String username, String password) throws Exception {
        boolean result = false;
        ftp = new FTPClient();
        int reply;
        ftp.connect(addr, port);
        ftp.login(username, password);
        ftp.enterLocalPassiveMode();//防止卡死 在上传下载前转换成被动模式
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return result;
        }
        ftp.changeWorkingDirectory(path);
        result = true;
        return result;
    }

    /**
     * @param file 上传的文件或文件夹
     * @throws Exception
     */
    private void uploadFile(File file) throws Exception {
        try {
            if (file.isDirectory()) {
                ftp.makeDirectory(file.getName());
                ftp.changeWorkingDirectory(file.getName());
                String[] files = file.list();
                for (int i = 0; i < files.length; i++) {
                    File file1 = new File(file.getPath() + "/" + files[i]);
                    if (file1.isDirectory()) {
                        uploadFile(file1);
                        ftp.changeToParentDirectory();
                    } else {
                        File file2 = new File(file.getPath() + "/" + files[i]);
                        FileInputStream input = new FileInputStream(file2);
                        ftp.storeFile(file2.getName(), input);
                        input.close();
                    }
                }
            } else {
                File file2 = new File(file.getPath());
                FileInputStream input = new FileInputStream(file2);
                ftp.storeFile(file2.getName(), input);
                input.close();
            }
        } finally {
            if(ftp !=null){
                try {
                    //递归上传文件这里不能关闭
//                    ftp.logout();
//                    ftp.disconnect();
                }catch (Exception e){
                    logger.error("ftpuploadfile:"+e);
                }
            }
        }
    }

    public void upload(File file) throws Exception {
        uploadFile(file);
        if(ftp !=null){
            try {
                ftp.logout();
                ftp.disconnect();
            }catch (Exception e){
                logger.error("ftpuploadfile:"+e);
            }
        }
    }

    public void uploadBj(File file) throws Exception {
        uploadFileBj(file);
        if(ftp !=null){
            ftp.logout();
            ftp.disconnect();
        }
    }

    /**
     * @param file 上传的文件或文件夹
     * @throws Exception
     */
    private void uploadFileBj(File file) throws Exception {
        try {
            if (file.isDirectory()) {
                ftp.makeDirectory(file.getName());
                ftp.changeWorkingDirectory(file.getName());
                String[] files = file.list();
                for (int i = 0; i < files.length; i++) {
                    File file1 = new File(file.getPath() + "/" + files[i]);
                    if (file1.isDirectory()) {
                        uploadFileBj(file1);
                        ftp.changeToParentDirectory();
                    } else {
                        String tempPath = file.getPath() + "/" + files[i];
                        uploadAndReNameFile(tempPath);
                    }
                }
            } else {
                String tempPath = file.getPath();
                uploadAndReNameFile(tempPath);
            }
        } finally {
            if(ftp !=null){
                try {
                    //递归上传文件这里不能关闭
//                    ftp.logout();
//                    ftp.disconnect();
                }catch (Exception e){
                    //e.printStackTrace();
                    logger.error("ftpuploadfile:"+e);
                }
            }
        }
    }

    private void uploadAndReNameFile(String tempPath) throws Exception {
        File file2 = new File(tempPath);
        FileInputStream input = new FileInputStream(file2);
        ftp.storeFile(file2.getName(), input);
        input.close();
//        String filePath=tempPath.substring(0,tempPath.length()-5);
//
//        String ftpTempPath=filePath.substring(filePath.indexOf("data")+4);
//        ftp.rename(ftpTempPath+".temp",filePath);
        if(!tempPath.endsWith(".ok")) {
            File fileOk = new File(tempPath + ".ok");
            FileUtils.writeStringToFile(fileOk, "ok");
            input = new FileInputStream(fileOk);
            ftp.storeFile(fileOk.getName(), input);
            input.close();
        }
    }

    public  void rename(String formPath,String toPath) throws IOException {
        ftp.rename(formPath,toPath);
        if(ftp !=null){
            ftp.logout();
            ftp.disconnect();
        }
    }

    /**
     * 下载链接配置
     * filename 为空下载所有remoteBaseDir下的文件
     * filename不为空只判断remoteBaseDir目录下是否有名字匹配
     * @param filename
     * @param localBaseDir 本地目录
     * @param remoteBaseDir 远程目录
     * @throws Exception
     */
    public  boolean startDown(String filename,String localBaseDir,String remoteBaseDir ) throws Exception{
        try {
            localBaseDir += "\\";
            FTPFile[] files = null;
            boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir);
            if (changedir) {
                ftp.setControlEncoding("GBK");
                files = ftp.listFiles();
                for (int i = 0; i < files.length; i++) {
                    try{
                        if(StringUtils.isEmpty(filename)){
                            downloadFile(files[i], localBaseDir, remoteBaseDir);
                        } else if(filename.equals(files[i].getName())){
                            downloadFile(files[i], localBaseDir, remoteBaseDir);
                            return true;
                        }
                    }catch(Exception e){
                        logger.error("<"+files[i].getName()+">下载失败",e);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("下载过程中出现异常",e);
        } finally {
            if(ftp !=null){
                ftp.logout();
                ftp.disconnect();
            }
        }

        return false;
    }

    /**
     *
     * 下载FTP文件
     * 当你需要下载FTP文件的时候,调用此方法
     * 根据<b>获取的文件名,本地地址,远程地址</b>进行下载
     *
     * @param ftpFile
     * @param relativeLocalPath
     * @param relativeRemotePath
     */
    private  void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) {
        if (ftpFile.isFile()) {
            if (ftpFile.getName().indexOf("?") == -1) {
                OutputStream outputStream = null;
                try {
                    File entryDir = new File(relativeLocalPath);
                    //如果文件夹路径不存在,则创建文件夹
                    if (!entryDir.exists() || !entryDir.isDirectory())
                    {
                        entryDir.mkdirs();
                    }
                    File locaFile= new File(relativeLocalPath+ ftpFile.getName());
                    //判断文件是否存在,存在则返回
                    if(locaFile.exists()){
                        return;
                    }else{
                        outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName());
                        ftp.retrieveFile(ftpFile.getName(), outputStream);
                        outputStream.flush();
                        outputStream.close();
                    }
                } catch (Exception e) {
                    logger.error("downloadFile",e);
                } finally {
                    try {
                        if (outputStream != null){
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        logger.error("输出文件流异常");
                    }
                }
            }
        } else {
            String newlocalRelatePath = relativeLocalPath + ftpFile.getName();
            String newRemote = new String(relativeRemotePath+ ftpFile.getName().toString());
            File fl = new File(newlocalRelatePath);
            if (!fl.exists()) {
                fl.mkdirs();
            }
            try {
                newlocalRelatePath = newlocalRelatePath + '/';
                newRemote = newRemote + "/";
                String currentWorkDir = ftpFile.getName().toString();
                boolean changedir = ftp.changeWorkingDirectory(currentWorkDir);
                if (changedir) {
                    FTPFile[] files = null;
                    files = ftp.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        downloadFile(files[i], newlocalRelatePath, newRemote);
                    }
                }
                if (changedir){
                    ftp.changeToParentDirectory();
                }
            } catch (Exception e) {
                logger.error("downloadFile",e);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        try {

            FtpUtil t = new FtpUtil();
            t.connect("/", "14.25.21.137", 21, "dt", "111");
            File file = new File("D:\\新建文件夹\\FJGJ");
            t.uploadBj(file);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值