`

edtFtp实现FTP工具类

    博客分类:
  • Java
 
阅读更多

edtFtp是一个开源的纯Java的FTP客户端类库。由于它实现了FTP协议,程序员可以通过它对远程FTP服务器进行访问,而不用再手工编写各种命令和处理服务器的回应。下面是我在实现开发中实现的一个FTP操作类,将其记录在此,方便以后使用。源代码如下:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.enterprisedt.net.ftp.FTPException;
import com.enterprisedt.net.ftp.FTPFile;
import com.enterprisedt.net.ftp.FileTransferClient;
import com.enterprisedt.net.ftp.FileTransferOutputStream;


/**
 * FTP服务器操作工具类
 * 
 * @author XXX
 * 
 */
public class FtpService
{

    private static final Log logger = LogFactory.getLog(FtpService.class
        .getName());
    // 部分静态常量
    private static final String SYSTEM_CONFIG_ITEM_FTPIP = "ip";
    private static final String SYSTEM_CONFIG_ITEM_FTPPORT = "port";
    private static final String SYSTEM_CONFIG_ITEM_FTPLOGINNAME = "username";
    private static final String SYSTEM_CONFIG_ITEM_FTPLOGINPWD = "password";
    private static final String SYSTEM_CONFIG_ITEM_PARAM_TYPE = "marketingActiveFtpParam";

    // FTP服务器IP地址
    private String ftpServiceIP;
    // FTP服务器端口
    private int ftpServicePort;
    // 登录账号
    private String loginUser;
    // 登录密码
    private String loginPwd;
    // FTP客户端对象
    private FileTransferClient ftpClient = null;
    // 单例对象
    private static FtpService ftpService = null;

    /**
     * 获取单例对象方法
     * 
     * @return
     * @throws Exception
     */
    public static synchronized FtpService getInstance() throws Exception
    {
        try
        {
            if (ftpService == null)
            {
                logger.info("从数据库获取FTP服务器相关配置,创建FTP客户端");
                String ftpServiceIP = SystemData.getParameterAPI().getParameterValue(SYSTEM_CONFIG_ITEM_PARAM_TYPE,SYSTEM_CONFIG_ITEM_FTPIP);
                int ftpServicePort = Integer.parseInt(SystemData.getParameterAPI().getParameterValue(SYSTEM_CONFIG_ITEM_PARAM_TYPE,SYSTEM_CONFIG_ITEM_FTPPORT));
                String loginUser = SystemData.getParameterAPI().getParameterValue(SYSTEM_CONFIG_ITEM_PARAM_TYPE,SYSTEM_CONFIG_ITEM_FTPLOGINNAME);
                String loginPwd = SystemData.getParameterAPI().getParameterValue(SYSTEM_CONFIG_ITEM_PARAM_TYPE,SYSTEM_CONFIG_ITEM_FTPLOGINPWD);
                ftpService = new FtpService(ftpServiceIP, ftpServicePort, loginUser, loginPwd);
            }
        }
        catch (Exception e)
        {
            throw new Exception("获取FTP服务器实例时异常,FTP服务器配置错误,请检查" + e);
        }
        return ftpService;
    }

    /**
     * 为了系统参数修改后,能创建新的Ftp客户端对象,特增加了此方法
     * 
     * @return
     * @throws Exception
     */
    public static synchronized FtpService getInstance(boolean isNew) throws Exception
    {
        try
        {
            
            if(isNew)
            {
                logger.info("从数据库获取FTP服务器相关配置,创建FTP客户端");
                String ftpServiceIP = SystemData.getParameterAPI().getParameterValue(SYSTEM_CONFIG_ITEM_PARAM_TYPE,SYSTEM_CONFIG_ITEM_FTPIP);
                int ftpServicePort = Integer.parseInt(SystemData.getParameterAPI().getParameterValue(SYSTEM_CONFIG_ITEM_PARAM_TYPE,SYSTEM_CONFIG_ITEM_FTPPORT));
                String loginUser = SystemData.getParameterAPI().getParameterValue(SYSTEM_CONFIG_ITEM_PARAM_TYPE,SYSTEM_CONFIG_ITEM_FTPLOGINNAME);
                String loginPwd = SystemData.getParameterAPI().getParameterValue(SYSTEM_CONFIG_ITEM_PARAM_TYPE,SYSTEM_CONFIG_ITEM_FTPLOGINPWD);
                ftpService = new FtpService(ftpServiceIP, ftpServicePort, loginUser, loginPwd);
            }
            else
                getInstance();
        }
        catch (Exception e)
        {
            throw new Exception("获取FTP服务器实例时异常,FTP服务器配置错误,请检查" + e);
        }
        return ftpService;
    }
    
    /**
     * 获取指定路径下指定目录或文件名称列表
     * 
     * @param dir:指定路径
     * @param directoryName:指定的目录名称,全称或部分
     * @return:名称列表
     */
    public synchronized List<String> getDirectoryListByDir(String dir,
        String directoryName) throws Exception
    {
        logger
            .info(String.format("从FTP服务上获取指定路径下的目录或文件名称列表,路径[%s],目录或文件名称[%s]。",
                dir, directoryName));
        List<String> allDirectorys = null;
        try
        {
            ftpClient.changeDirectory(dir);
            FTPFile[] files = ftpClient.directoryList(directoryName.trim());
            int length = files.length;
            if (length > 0)
            {
                allDirectorys = new ArrayList<String>();
                for (int i = 0; i < length; i++)
                {
                    allDirectorys.add(files[i].getName().trim());
                }
            }
            changeToRootDirectoryByDir(dir);
        }
        catch (Exception e)
        {
            throw new Exception("获取指定路径下指定目录名称列表时发生异常,原因:" + e);
        }

        return allDirectorys;
    }

    /**
     * 将FTP服务器指定目录下的指定文件下载到本地指定的文件中并将FTP上的文件删除掉
     * 
     * @param dir:FTP服务器上目录
     * @param localFileName:存放到本地的文件名称(包含存放的路径,如无路径则默认为当前路径)
     * @param remoteFileName:FTP服务器上的文件名称
     */
    public synchronized void downloadRemoteFileToLocalAndDeleteIt(String dir,
        String localTempProcessFileName, String localBackupFileName,
        String remoteFileName) throws Exception
    {
        logger
            .info(String
                .format(
                    "将FTP服务器指定目录下的指定文件下载到本地指定的文件中并将FTP上的文件删除掉,FTP服务器目录[%s],远程文件名[%s],本地文件名[%s]。",
                    dir, remoteFileName, localTempProcessFileName));
        try
        {
            ftpClient.changeDirectory(dir);
            boolean isExists = ftpClient.exists(remoteFileName);
            if (!isExists)
            {
                logger.info(remoteFileName + "文件在FTP服务器目录" + dir
                    + "不存在,请检查FTP服务器");
                return;
            }
            ftpClient.downloadFile(localTempProcessFileName, remoteFileName);
            logger.info("已将FTP服务器上的文件" + remoteFileName + "下载到本地文件"
                + localTempProcessFileName);
            ftpClient.downloadFile(localBackupFileName, remoteFileName);

            ftpClient.deleteFile(remoteFileName);
            logger.info("已将FTP服务器上的文件" + remoteFileName + "删除");
            changeToRootDirectoryByDir(dir);
        }
        catch (Exception e)
        {
            throw new Exception("将FTP服务器指定目录下的指定文件下载到本地指定的文件时发生异常,原因:" + e);
        }
    }

    /**
     * 将FTP服务器上的文件下载到本地
     * 
     * @param remoteFileName
     * @param localFileName
     * @throws Exception
     */
    public synchronized boolean downloadRemotFileToLocal(String remoteFileName,
        String localFileName) throws Exception
    {
        logger.info(String.format("将FTP服务器上的文件下载到本地,远程文件名[%s],本地文件名[%s]。",
            remoteFileName, localFileName));
        String msg = "";
        try
        {
            // connectToServer();
            boolean isExists = ftpClient.exists(remoteFileName);
            if (!isExists)
            {
                msg = remoteFileName + "文件在FTP服务器上不存在,请检查FTP服务器";
                logger.info(msg);
               throw new RuntimeException(msg);
            }
            ftpClient.downloadFile(localFileName, remoteFileName);
            logger.info("已将FTP服务器上的文件" + remoteFileName + "下载到本地文件"
                + localFileName);
        }
        catch (RuntimeException e)
        {
            msg = "将FTP服务器上文件下载到本地时发生异常,原因:" + e.getMessage();
            logger.info(msg);
           throw new RuntimeException(msg);
        }
        return true;
    }

    /**
     * 将指定的本地文件上传到FTP服务器上
     * 
     * @param localFileName
     * @param remoteFileName
     */
    public synchronized void uploadFileToFtpServer(String localFileName,
        String remoteFileName) throws Exception
    {
        logger.info(String.format("将指定的本地文件上传到FTP服务器上,本地文件名[%s],远程文件名[%s]。",
            localFileName, remoteFileName));
        try
        {
            ftpClient.uploadFile(localFileName, remoteFileName);
            logger.info("成功将文件" + localFileName + "上传到FTP服务器");
        }
        catch (Exception e)
        {
            throw new Exception("将指定的本地文件上传到FTP服务器上时发生异常,原因:" + e);
        }
    }

    /**
     * 将内容串上传到FTP服务器
     * 
     * @param remoteFileName
     * @param allContents
     * @throws Exception
     */
    public synchronized void uploadContentsToFtpServer(String remoteFileName,
        String allContents) throws Exception
    {
        logger.info(String.format("将内容串上传到FTP服务器上指定的文件中,远程文件名[%s],内容串[%s]。",
            remoteFileName, allContents));
        FileTransferOutputStream outputStream = null;
        try
        {
            outputStream = ftpClient.uploadStream(remoteFileName);
            outputStream.write(allContents.getBytes());
            outputStream.flush();

            logger.info("成功将文件" + remoteFileName + "上传到FTP服务器");
        }
        catch (Exception e)
        {
            throw new Exception("将内容上传到FTP服务器上时发生异常,原因:" + e);
        }
        finally
        {
            if (outputStream != null)
            {
                outputStream.close();
                outputStream = null;
            }
        }
    }

    /**
     * 根据传入的目录路径返回到FTP服务器根目录,供下次使用
     * 
     * @param dir
     * @throws FTPException
     * @throws IOException
     */
    private synchronized void changeToRootDirectoryByDir(String dir)
        throws FTPException, IOException
    {
        logger
            .info(String.format("根据传入的目录路径返回到FTP服务器根目录,供下次使用,当前路径[%s]。", dir));
        int parentLevels = dir.split("/").length;
        for (int i = 0; i < parentLevels; i++)
            ftpClient.changeToParentDirectory();
    }

    /**
     * 连接FTP服务器,并登录服务器
     * 
     * @throws FTPException
     * @throws IOException
     */
    public synchronized void connectToServer() throws Exception
    {
        ftpClient = new FileTransferClient();
        try
        {
            ftpClient.setRemoteHost(ftpServiceIP);
            ftpClient.setRemotePort(ftpServicePort);
            ftpClient.setUserName(loginUser);
            ftpClient.setPassword(loginPwd);
            ftpClient.connect();
            logger.info(String.format("连接并登录到FTP服务器,IP[%s],Port[%d],User[%s]。",
                ftpServiceIP, ftpServicePort, loginUser));
        }
        catch (Exception e)
        {
            ftpService = null;
            throw new Exception("连接和登录FTP服务器时发生异常,请检查FTP服务器参数配置,原因:" + e);
        }
    }

    /**
     * 断开与FTP服务器的连接
     * 
     * @throws FTPException
     * @throws IOException
     */
    public synchronized void disconnectToServer() throws Exception
    {
        try
        {
            if (ftpClient != null)
            {
                if (ftpClient.isConnected())
                {
                    ftpClient.disconnect();
                    ftpClient = null;
                    logger.info("断开与FTP服务器连接");
                }
            }
        }
        catch (Exception e)
        {
            throw new Exception("断开与FTP服务器连接时发生异常,原因:" + e);
        }
    }

    /**
     * 无参私有构造器
     */
    private FtpService()
    {
        super();
    }

    /**
     * 全参私有构造器
     * 
     * @param ftpServiceIP
     * @param ftpServicePort
     * @param loginUser
     * @param loginPwd
     */
    private FtpService(String ftpServiceIP, int ftpServicePort,
        String loginUser, String loginPwd)
    {
        super();
        this.ftpServiceIP = ftpServiceIP;
        this.ftpServicePort = ftpServicePort;
        this.loginUser = loginUser;
        this.loginPwd = loginPwd;
    }
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics