FTP上传下载工具类

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

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

/**
 * Ftp上传下载文件
 * 
 * @author sww
 * @version C01 2014年8月14日
 * @since PhonePlus
 */
public class FTPUtil
{
    private final Logger logger = Logger.getLogger(FTPUtil.class);
    
    /**
     * FTP服务地址
     */
    private  String address;

    /**
     * FTP端口号
     */
    private int port;

    /**
     * FTP登录用户名
     */
    private String username;

    /**
     * FTP登录密码
     */
    private String password;

    /**
     * 构造函数 
     */
    public FTPUtil(String address, int port, String username, String password)
    {
        this.address = address;
        this.port = port;
        this.username = username;
        this.password = password;
    }
    
    /**
     * 
     * 获取FTP连接
     * 
     * @author sww
     * @return
     */
    private FTPClient getClient()
    {
        FTPClient ftp = new FTPClient();
        try
        {
            ftp.connect(address, port);
            // 登录
            ftp.login(username, password);
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        }
        catch (SocketException e)
        {
            e.printStackTrace();
            logger.error("Login Fail FTP :" + address, e);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            logger.error("Login FTP Fail ! IOException", e);
        }
        return ftp;
    }

    /**
     * 
     * Ftp服务器文件移动
     * @author sww
     * @param from
     * @param to
     * @param fileExtension
     * @return
     */
    public boolean moveFile(String from, String to, String fileExtension)
    {
        logger.info("FTP moveFile from :" + from + " to:" + to);
        boolean success = false;
        FTPClient ftp = getClient();
        try
        {
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                logger.error("Ftp not response :" + reply);
                return success;
            }
            ftp.changeWorkingDirectory(from);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs)
            {
                if (ff.getName().endsWith(fileExtension))
                {
                    ftp.makeDirectory(to);
                    ftp.rename(from + File.separator + ff.getName(), to + File.separator + ff.getName());
                }
            }

            ftp.logout();
            success = true;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            logger.error("Ftp moveFile Exception !", e);
        }
        finally
        {
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException ioe)
                {
                    logger.error("Ftp moveFile disconnect ftp Exception !", ioe);
                }
            }
        }
        return success;
    }

    /**
     * Description: 向FTP服务器上传文件
     * 
     * @param formLocal
     *            本地文件目录
     * @param toRemote
     *            FTP服务器保存目录
     * @param fileExtension
     *            要上传的文件名的后缀名
     * @return 成功返回true,否则返回false
     */
    public boolean uploadFile(String formLocal, String toRemote, String fileExtension)
    {
        logger.info("FTP uploadFile from :" + formLocal + " to:" + toRemote);
        boolean success = false;
        FTPClient ftp = getClient();
        try
        {
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                logger.error("Ftp not response :" + reply);
                return success;
            }
            File local = new File(formLocal);
            if (!local.exists())
            {
                logger.error("local path not exist !");
                return false;
            }
            File[] dirFile = local.listFiles();
            int upCount = 0;
            for (File f : dirFile)
            {
                if (f.getName().endsWith(fileExtension))
                {
                    InputStream in = new FileInputStream(f);
                    ftp.changeWorkingDirectory(toRemote);
                    ftp.storeFile(f.getName(), in);
                    upCount++;
                    in.close();
                }
            }

            ftp.logout();
            if (upCount == 0)
            {
                logger.error(fileExtension + " file upload fail !");
            }
            else
            {
                success = true;
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
            logger.error("Ftp uploadFile Exception !", e);
        }
        finally
        {
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException ioe)
                {
                    logger.error("Ftp uploadFile disconnect ftp Exception !", ioe);
                }
            }
        }
        return success;
    }

    /**
     * Description: 从FTP服务器下载文件
     * 
     * @param formRemote
     *            FTP服务器上的相对路径
     * @param toLocal
     *            下载后保存到本地的路径
     * @param fileExtension
     *            要下载的文件名的后缀名
     * @return
     */
    public boolean downFile(String formRemote, String toLocal, String fileExtension)
    {
        boolean success = false;
        FTPClient ftp = getClient();
        try
        {
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                logger.error("Ftp not response :" + reply);
                return success;
            }
            File local = new File(toLocal);
            if (!local.exists())
            {
                logger.error("local path not exist !");
                return false;
            }
            ftp.changeWorkingDirectory(formRemote);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            int downCount = 0;
            for (FTPFile ff : fs)
            {
                if (ff.getName().endsWith(fileExtension))
                {
                    File localFile = new File(toLocal + "/" + ff.getName());
                    OutputStream is = new FileOutputStream(localFile);
                    ftp.retrieveFile(ff.getName(), is);
                    downCount++;
                    is.close();
                }
            }
            ftp.logout();
            if (downCount == 0)
            {
                logger.error(fileExtension + " file download fail !");
            }
            else
            {
                success = true;
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
            logger.error("Ftp downFile Exception !", e);
        }
        finally
        {
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException ioe)
                {
                    logger.error("Ftp downFile disconnect ftp Exception !", ioe);
                }
            }
        }
        return success;
    }

}


依赖jar包:commons-net-1.4.1.jar  jakarta-oro-2.0.8.jar

下载地址:http://download.csdn.net/detail/osmartshen/7781831

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值