博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

ftp使用

Posted on 2019-07-26 15:07  激流勇进、  阅读(228)  评论(0编辑  收藏  举报

1.pom文件中添加依赖

 

<!-- ftp使用 -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>


2.代码样例:

package com.migu.reading.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import com.migu.reading.iufs.domain.InviteResultCode;
import com.migu.reading.iufs.domain.IufsException;

import java.io.*;
import java.net.SocketException;

public class FtpUtil
{
    
    private static final Log LOGGER = LogFactory.getLog(FtpUtil.class);
    
    /**
    * 获取FTPClient对象
    * 
    * @param ftpHost
    *            FTP主机服务器
    * @param ftpPassword
    *            FTP 登录密码
    * @param ftpUserName
    *            FTP登录用户名
    * @param ftpPort
    *            FTP端口 默认为21
    * @return
     * @throws IOException 
     * @throws Exception 
    */
    public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort)
    {
        FTPClient ftpClient = new FTPClient();
        try
        {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
            {
                LOGGER.info("未连接到FTP,用户名或密码错误。");
                ftpClient.disconnect();
            }
            else
            {
                LOGGER.info("FTP连接成功。");
            }
        }
        catch (SocketException e)
        {
            LOGGER.error("FTP的IP地址可能错误,请正确配置。e:{}" + e);
        }
        catch (IOException e)
        {
            LOGGER.error("FTP的端口错误,请正确配置。e:{}" + e);
        }
        return ftpClient;
    }
    
    /**
     * 下载文件
     * 
     * @param ftpHost ftp服务器地址
     * @param ftpUserName 用户名
     * @param ftpPassword 指定用户密码
     * @param ftpPort ftp服务器端口号
     * @param ftpPath  ftp文件存放物理路径
     * @param localPath 下载到的本地路径
     */
    public static boolean downloadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort,
        String ftpPath, String localPath)
    {
        FTPClient ftpClient = null;
        boolean result = false;
        boolean createOrExistsDir = FileTools.createOrExistsDir(localPath);
        if (!createOrExistsDir)
        {
            LOGGER.error("FtpUtil.downloadFile create localPath error");
            return result;
        }
        try
        {
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            // 设置被动模式,开通一个端口来传输数据
            ftpClient.enterLocalPassiveMode();
            ftpClient.setControlEncoding("UTF-8"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setBufferSize(500);
            // 截取路径
            String path = ftpPath.substring(0, ftpPath.lastIndexOf("/") + 1);
            boolean changeWorkingDirectory =
                ftpClient.changeWorkingDirectory(new String(path.getBytes(), "ISO-8859-1"));
            
            if (changeWorkingDirectory)
            {
                File ftpPathFile = new File(ftpPath);
                File localFile = new File(localPath + "/" + ftpPathFile.getName());
                
                FileOutputStream os = new FileOutputStream(localFile);
                String ftpPathFileName = new String(ftpPathFile.getName().getBytes("UTF-8"), "ISO-8859-1");
                result = ftpClient.retrieveFile(ftpPathFileName, os);
                os.close();
                ftpClient.logout();
            }
            else
            {
                LOGGER.error("FtpUtil.downloadFile ftpPath is error");
                throw new IufsException(InviteResultCode.FTP_PATH_ERROR.getCode(),
                    InviteResultCode.FTP_PATH_ERROR.getDesc());
            }
            // ftpClient.listDirectories()
            // 判断文件是否存在
            // String file = ftpPath.substring(ftpPath.lastIndexOf("/") + 1);
            // //
            // InputStream is =
            // ftpClient.retrieveFileStream(new String(file.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
            // if (is == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE)
            // {
            // throw new IufsException(InviteResultCode.FTP_PATH_ERROR.getCode(),
            // InviteResultCode.FTP_PATH_ERROR.getDesc());
            // }
            // is.close();
            // ftpClient.completePendingCommand();
            
            return result;
        }
        catch (FileNotFoundException e)
        {
            LOGGER.error("没有找到" + ftpPath + "文件,e:{}", e);
            return false;
        }
        catch (SocketException e)
        {
            LOGGER.error("连接FTP失败.e:{}", e);
            return false;
        }
        catch (IOException e)
        {
            LOGGER.error("文件读取错误。e:{}", e);
            return false;
        }
    }
    
    /**
     * 上传文件
     * 
     * @param ftpHost ftp服务器地址
     * @param ftpUserName anonymous匿名用户登录,不需要密码。administrator指定用户登录
     * @param ftpPassword 指定用户密码
     * @param ftpPort ftp服务员器端口号
     * @param ftpPath  ftp文件存放物理路径
     * @param fileName 文件路径
    
     */
    public static void uploadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath,
        String fileName, InputStream input)
    {
        FTPClient ftp = null;
        try
        {
            ftp = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            ftp.changeWorkingDirectory(ftpPath);
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
            boolean storeFile = ftp.storeFile(fileName, input);
            System.out.println("是否上传成功--" + storeFile);
            input.close();
            ftp.logout();
            System.out.println("upload succes!");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    @SuppressWarnings("unused")
    private static boolean downFileOrDir(String ftpFilePath, String localDir, String ftpHost, String ftpUserName,
        String ftpPassword, int ftpPort)
    {
        
        boolean result = true;
        
        FileOutputStream fos = null;
        FTPClient ftpClient = null;
        try
        {
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            
            File file = new File(ftpFilePath);
            File temp = new File(localDir);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setBufferSize(1024);
            // 设置文件类型(二进制)
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            
            if (!temp.exists())
            {
                if (!temp.mkdirs())
                {
                }
            }
            // 如果不是目录则表示是单个文件的下载
            String filePathsss = ftpFilePath.substring(0, ftpFilePath.lastIndexOf("/") + 1);
            boolean b = ftpClient.changeWorkingDirectory(filePathsss);
            if (!b)
            {
                LOGGER.error("------------ftpFile not exists-------------");
                // 报错
            }
            String[] names = ftpClient.listNames();
            for (String name : names)
            {
                if (file.getName().equals(name))
                {
                    File localfile = new File(localDir + File.separator + file.getName());
                    if (!localfile.exists())
                    {
                        fos = new FileOutputStream(localfile);
                        result = ftpClient.retrieveFile(file.getName(), fos);
                    }
                    else
                    {
                        if (!localfile.delete())
                        {
                        }
                        fos = new FileOutputStream(localfile);
                        result = ftpClient.retrieveFile(file.getName(), fos);
                    }
                    ftpClient.changeToParentDirectory();
                    return result;
                }
            }
        }
        catch (IOException e)
        {
            try
            {
                if (null != fos)
                {
                    fos.close();
                }
            }
            catch (IOException e1)
            {
            }
            result = false;
        }
        catch (Exception e)
        {
            result = false;
        }
        finally
        {
            try
            {
                if (null != fos)
                {
                    fos.close();
                }
            }
            catch (IOException e)
            {
            }
        }
        return result;
    }
    
    public static void main(String[] args)
    {
        /*****下载文件*********/
        // boolean downloadFile = downloadFile("10.211.93.173",
        // "commonservice",
        // "1qaz@WSX",
        // 21,
        // "/home/commonservice/data/vcode/muban.zip",
        // "D://file");
        // System.out.println("是否下载成功===》" + downloadFile);
        
        // boolean downloadFile = downFileOrDir("/home/commonservice/data/vcode/vcodeTemplate20190402162646.zip",
        // "D://file",
        // "10.211.93.173",
        // "commonservice",
        // "1qaz@WSX",
        // 21);
        // System.out.println(downloadFile);
        // "ftp://10.211.93.173/aa.zip"
        // "ftp://10.211.93.173/copyrights_exportFile/Copyrights_20171101164204.zip",
        // boolean downloadFile =
        // downFileOrDir("ftp://10.211.93.173/aa.zip", "D://file", "10.211.93.173", "commonservice", "1qaz@WSX", 21);
        // System.out.println(downloadFile);
        
        /********上传******************/
        // String filePath = "D:\\file";
        // String fileName = "muban.zip";
        // FileInputStream input = null;
        // try
        // {
        // input = new FileInputStream(new File(filePath + File.separatorChar + fileName));
        // }
        // catch (FileNotFoundException e)
        // {
        // e.printStackTrace();
        // }
        // uploadFile("10.211.93.173",
        // "commonservice",
        // "1qaz@WSX",
        // 21,
        // "/home/commonservice/data/vcode/",
        // fileName,
        // input);
    }
}