java FTP下载,兼容linux和Windows环境

java FTP下载,兼容linux和Windows环境

FTPUtil类:


import org.apache.commons.net.ftp.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import sun.net.TelnetInputStream;

import java.io.*;
import java.util.Calendar;
import java.util.TimeZone;

/**
 * Ftp工具类
 *
 * @Author Samuel
 * @Date 2018-10-31
 */

public class FtpUtil {

    private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);

    private FTPClient ftpClient;
    @Autowired(required = false)
    private String address;

    private int port;

    private String username;

    private String password;

    private String basepath;

    private String clientConfig;

    /* *
     * Ftp构造函数
     */
    public FtpUtil(String address, int port, String username, String Password, String basepath,String clientConfig) {
        this.address = address;
        this.port = port;
        this.username = username;
        this.password = Password;
        this.basepath = basepath;
        this.clientConfig = clientConfig;
        this.ftpClient = new FTPClient();
    }

    public FtpUtil(String address, int port, String username, String Password, String basepath) {
        this.address = address;
        this.port = port;
        this.username = username;
        this.password = Password;
        this.basepath = basepath;
        this.ftpClient = new FTPClient();
    }

    /**
     * @return 判断是否登入成功
     */
    public boolean ftpLogin() {
        long start = System.currentTimeMillis();
        boolean isLogin = false;
        FTPClientConfig ftpClientConfig = new FTPClientConfig();
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
        this.ftpClient.setControlEncoding("GBK");
        this.ftpClient.configure(ftpClientConfig);
        try {
            if (this.port > 0) {
                this.ftpClient.connect(this.address, this.port);
            } else {
                this.ftpClient.connect(this.address);
            }
            // FTP服务器连接回答
            int reply = this.ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.ftpClient.disconnect();
                logger.error("登录FTP服务失败!");
                return isLogin;
            }
            //TimeUnit.SECONDS.sleep(2);
            isLogin = this.ftpClient.login(this.username, this.password);
            if(!isLogin){
                logger.error("登录FTP服务失败!");
                return isLogin;
            }
            // 设置传输协议
            this.ftpClient.enterLocalPassiveMode();
            isLogin = this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            if(!isLogin){
                logger.error("登录FTP服务失败!");
                return isLogin;
            }
            logger.info(this.username + "成功登陆FTP服务器");
            logger.info("登录耗时:***********"+(System.currentTimeMillis()-start)+"毫秒");
        } catch (Exception e) {
            logger.error(this.username + "登录FTP服务失败!" + e.getMessage());
        }
        this.ftpClient.setBufferSize(1024 * 2);
        this.ftpClient.setDataTimeout(30 * 1000);
        return isLogin;
    }

    /**
     * @退出关闭服务器链接
     */
    public void ftpLogOut() {
        if (null != this.ftpClient && this.ftpClient.isConnected()) {
            try {
                boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
                if (reuslt) {
                    logger.info("成功退出服务器");
                }
            } catch (IOException e) {
                e.printStackTrace();
                logger.warn("退出FTP服务器异常!" + e.getMessage());
            } finally {
                try {
                    this.ftpClient.disconnect();// 关闭FTP服务器的连接
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.warn("关闭FTP服务器的连接异常!");
                }
            }
        }
    }

    /***
     * 上传Ftp文件
     * @param romotUpLoadePath 上传服务器路径(以/结束)
     * */
    public boolean uploadFile(File localFile, String romotUpLoadePath) {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
//            success = this.ftpClient.makeDirectory(romotUpLoadePath);
            success = this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
            if(!success){
                logger.error("changeWorkingDirectory方法异常");
                return success;
            }
            inStream = new BufferedInputStream(new FileInputStream(localFile));
            logger.info(localFile.getName() + "开始上传.....");
            success = this.ftpClient.storeFile(localFile.getName(), inStream);
            if(!success){
                logger.error("storeFile方法异常");
                return success;
            }
            if (success == true) {
                logger.info(localFile.getName() + "上传成功");
            }else{
                logger.info(localFile.getName() + "上传失败");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            logger.error(localFile + "未找到");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }

    /***
     * 下载文件
     * @param remoteFileName   待下载文件名称
     * @param localDires 下载到当地那个路径下
     * @param remoteDownLoadPath remoteFileName所在的路径
     * */

    public boolean downloadFile(String remoteFileName, String localDires,
                                String remoteDownLoadPath) {
        String strFilePath = localDires + remoteFileName;
        BufferedOutputStream outStream = null;
        boolean success = false;
        try {
            this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
            File targetFile = new File(strFilePath);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            outStream = new BufferedOutputStream(new FileOutputStream(
                    strFilePath));
            logger.info(remoteFileName + "开始下载....");
            success = this.ftpClient.retrieveFile(remoteFileName, outStream);
            if (success == true){
                logger.info(remoteFileName + "成功下载到" + strFilePath);
                return success;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(remoteFileName + "下载失败");
        } finally {
            if (null != outStream) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (success == false) {
            logger.error(remoteFileName + "下载失败!!!");
        }
        return success;
    }

    /***
     * @上传文件夹
     * @param localDirectory
     *            本地文件夹
     * @param remoteDirectoryPath
     *            Ftp 服务器路径 以目录"/"结束
     * */
    public boolean uploadDirectory(String localDirectory,
                                   String remoteDirectoryPath) {
        File src = new File(localDirectory);
        try {
            remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
            this.ftpClient.makeDirectory(remoteDirectoryPath);
            // ftpClient.listDirectories();
        } catch (IOException e) {
            e.printStackTrace();
            logger.info(remoteDirectoryPath + "目录创建失败");
        }
        File[] allFile = src.listFiles();
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
            if (!allFile[currentFile].isDirectory()) {
                String srcName = allFile[currentFile].getPath().toString();
                uploadFile(new File(srcName), remoteDirectoryPath);
            }
        }
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
            if (allFile[currentFile].isDirectory()) {
                // 递归
                uploadDirectory(allFile[currentFile].getPath().toString(),
                        remoteDirectoryPath);
            }
        }
        return true;
    }

    /***
     * @下载文件夹
     * @param localDirectoryPath 本地地址
     * @param remoteDirectory 远程文件夹
     * */
    public boolean downLoadDirectory(String localDirectoryPath, String remoteDirectory) {
        try {
            String fileName = new File(remoteDirectory).getName();
            localDirectoryPath = localDirectoryPath + fileName + "//";
            new File(localDirectoryPath).mkdirs();
            FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (!allFile[currentFile].isDirectory()) {
                    downloadFile(allFile[currentFile].getName(), localDirectoryPath, remoteDirectory);
                }
            }
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (allFile[currentFile].isDirectory()) {
                    String strremoteDirectoryPath = remoteDirectory + "/" + allFile[currentFile].getName();
                    downLoadDirectory(localDirectoryPath, strremoteDirectoryPath);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("下载文件夹失败");
            return false;
        }
        return true;
    }

    // FtpClient的Set 和 Get 函数
    public FTPClient getFtpClient() {
        return ftpClient;
    }

    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }

    public static void main(String[] args) throws IOException {
        FtpUtil ftp = new FtpUtil("120.78.147.127", 21, "Administrator", "Gkxygkxy123456","","UNIX");
        ftp.ftpLogin();
        FTPClient ftpClient=new FTPClient();
        ftpClient.connect("120.78.147.127",21);
        ftpClient.login("Administrator","Gkxygkxy123456");
        int ch;
        ch=ftpClient.getReplyCode();
        if(! FTPReply.isPositiveCompletion(ch)){
            ftpClient.disconnect();
        }
        logger.info("ftp链接成功");
        FTPFile[] fs=ftpClient.listFiles();
   //     ftp.fileDown("D://test","20190123151628.xml","remoteDownLoadPath");
//        ftp.uploadFile(new File("E:\\txt\\abcdetest.txt"),"txt");
        ftp.ftpLogOut();
        //上传文件夹
        //ftp.uploadDirectory("d://DataProtemp", "/home/data/");
        //下载文件夹
//String loc="D:/downFile";
//
//String url="/demo.txt";
//       int index= url.lastIndexOf("/");
//        String arc=url.substring(0,index);
//        String file=url.substring(index+1,url.length());
//        logger.info(index+"文件名:"+file+"   相对路径:"+arc);
       //boolean ok= ftp.fileDown(loc,"demo.txt","/business");
        //logger.info("========"+ok);
        //ftp.downloadFile("test","C://ftp//","C:/ftp/test.txt");
        //ftp.downLoadDirectory("d://tmp//", "/home/data/DataProtemp");
        //File local = new File("C:\\Users\\Administrator\\Desktop\\问题记录.txt");
//        ftp.uploadDirectory("C:\\Users\\Administrator\\Desktop\\问题记录.txt","\\20181204\\");

        //ftp.ftpLogOut();
    }

    /**
     *
     * @param loclDires 文件保存的本地路径
     * @param fileName  待下载的文件名
     * @param fileUrl  待下载文件在ftp服务器上的相对路径
     * @return
     */
    public  boolean fileDown(String loclDires,String fileName,String fileUrl){
        TelnetInputStream fget=null;
        RandomAccessFile getFile=null;
        FTPClient ftpClient=null;
        boolean success=false;
        Calendar calendar= Calendar.getInstance();
        String date="/"+ calendar.get(Calendar.YEAR)+(calendar.get(Calendar.MONTH)+1)+calendar.get(Calendar.DATE);
        loclDires = loclDires+date;
        int ch;
        if(! new File(loclDires).isDirectory()){
                new File(loclDires).mkdir();
        }
        String keepLocate=loclDires+"/"+fileName;
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(address,port);
            ftpClient.login(username,password);
            ch=ftpClient.getReplyCode();
            if(! FTPReply.isPositiveCompletion(ch)){
                ftpClient.disconnect();
                return success;
            }
            logger.info("ftp链接成功");
            ftpClient.changeWorkingDirectory(fileUrl);
                FTPFile[] fs=ftpClient.listFiles();
            for (FTPFile ff:fs) {
                if(ff.getName().equals(fileName)){
                    logger.info("找到目标文件:"+fileName);
                    File licalFile=new File(loclDires+"/"+ff.getName());
                    OutputStream is =new FileOutputStream(licalFile);
                    ftpClient.retrieveFile(ff.getName(),is);
                    is.close();
                    success=true;
                    break;
                }
            }
            ftpClient.logout();
        } catch (IOException e) {
           logger.error("ftp文件下载出错:"+e.getMessage());
            success=false;
        }finally {
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    logger.error("ftp服务关闭出错:"+e.getMessage());
                }
            }
        }
        return success;
    }

    public File getSchemeFile(String fileName , String fileUrl){
        int ch;
        try {
            this.ftpClient.connect(this.address,this.port);
            boolean flag = this.ftpClient.login(this.username,this.password);
            if(!flag){
                logger.error("登录FTP失败。");
                return null;
            }
            //设置FTP服务器环境
            FTPClientConfig ftpClientConfig = new FTPClientConfig(this.clientConfig);
            this.ftpClient.configure(ftpClientConfig);

            this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ch=ftpClient.getReplyCode();
            if(! FTPReply.isPositiveCompletion(ch)){
                this.ftpClient.disconnect();
                return null;
            }
            logger.info("ftp链接成功");

            //设置访问被动模式
            this.ftpClient.setRemoteVerificationEnabled(false);
            this.ftpClient.enterLocalPassiveMode();
            this.ftpClient.setControlEncoding("GBK");
            //this.ftpClient.enterLocalPassiveMode();
            boolean flag2 = this.ftpClient.changeWorkingDirectory(new String(fileUrl.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
            if(!flag2){
                logger.error("changeWorkingDirectory方法出错!");
                return null;
            }
            logger.info("changeWorkingDirectory:"+fileUrl);
            FTPFile[] fs=this.ftpClient.listFiles();
            for (FTPFile ff:fs) {
                logger.info("文件名:"+ff.getName());
                if((java.net.URLDecoder.decode(ff.getName(),"UTF-8")).equals(fileName)){
                    logger.info("找到目标文件:"+fileName);
                    File localFile=new File(java.net.URLDecoder.decode(ff.getName(),"UTF-8"));
                    OutputStream outputStream =new FileOutputStream(localFile);
                    String remoteFileName = java.net.URLDecoder.decode(ff.getName(),"UTF-8");
                    this.ftpClient.retrieveFile(new String(remoteFileName.getBytes("GBK"),"iso-8859-1"),outputStream);//下载必须转码
                    outputStream.close();
                    this.ftpClient.logout();
                    return localFile;
                }
            }
            this.ftpClient.logout();
            logger.info("无法找到目标文件:"+fileName);
        } catch (IOException e) {
            logger.error("ftp文件下载出错:"+e.getMessage());
        } finally {
            if(this.ftpClient.isConnected()){
                try {
                    this.ftpClient.disconnect();
                } catch (IOException e) {
                    logger.error("ftp服务关闭出错:"+e.getMessage());
                }
            }
        }
        return null;
    }


}

其中ftp服务器环境分:

   public static final String SYST_UNIX = "UNIX";
    public static final String SYST_VMS = "VMS";
    public static final String SYST_NT = "WINDOWS";
    public static final String SYST_OS2 = "OS/2";
    public static final String SYST_OS400 = "OS/400";
    public static final String SYST_AS400 = "AS/400";
    public static final String SYST_MVS = "MVS";
    public static final String SYST_L8 = "TYPE: L8";
    public static final String SYST_NETWARE = "NETWARE";
    public static final String SYST_MACOS_PETER = "MACOS PETER";

调用方法:

 boolean flag = false;
        FtpUtil ftp = new FtpUtil(FTPAddress, FTPPort, FTPUsername, FTPPassword, "",clientConfig);
        flag = ftp.ftpLogin();
        if (flag) {
            File file = ftp.getSchemeFile(fileName, FTPUploadtaskschemepath);
                   }
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值