聚合支付-ftp下載功能

原文鏈接:https://blog.csdn.net/forever_yours/article/details/78605205 

package com.zhsoft.rightPay.acq.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

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

public class FtpUtil {
    private static Logger logger = Logger.getLogger(FtpUtil.class);


    private static FTPClient ftp;

    /**
     * 獲取ftp連接
     * 
     * @param f
     * @return
     * @throws Exception
     */
    public static boolean connectFtp() throws Exception {
        String host="file.ipaynow.cn";
        int port=22;
        String user="00000000155";
        String password="zipfapdslafoW3z2";
        String romotePath="/agentbusi";
        ftp = new FTPClient();
        boolean flag = false;
        int reply;
        ftp.connect(host, port);
        ftp.login(user, password);
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        //設置linux環境
        FTPClientConfig conf = new FTPClientConfig( FTPClientConfig.SYST_UNIX);
        ftp.configure(conf);
        //判斷是否連接成功
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return flag;
        }
        ftp.changeWorkingDirectory(romotePath);
        flag = true;
        return flag;
    }

    /**
     * 關閉ftp連接
     */
    public static void closeFtp() {
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * ftp上傳文件
     * 
     * @param f
     * @throws Exception
     */
    public static void upload(File f) throws Exception {
        if (FtpUtil.connectFtp()) {
        if (f.isDirectory()) {
            ftp.makeDirectory(f.getName());
            ftp.changeWorkingDirectory(f.getName());
            String[] files = f.list();
            for (String fstr : files) {
                File file1 = new File(f.getPath() + "/" + fstr);
                if (file1.isDirectory()) {
                    upload(file1);
                    ftp.changeToParentDirectory();
                } else {
                    File file2 = new File(f.getPath() + "/" + fstr);
                    FileInputStream input = new FileInputStream(file2);
                    ftp.storeFile(file2.getName(), input);
                    input.close();
                }
            }
        } else {
            FileInputStream input = new FileInputStream(f);
            ftp.storeFile(f.getName(), input);
            input.close();
            closeFtp();
        }
        }
    }

    /**
     * 下載鏈接配置
     * 
     *
     * @param localBaseDir
     *            本地目錄
     * @param remoteBaseDir
     *            遠程目錄
     * @throws Exception
     */
    public static void startDown( String localBaseDir, String remoteBaseDir) throws Exception {
        if (FtpUtil.connectFtp()) {
            try {
                // 設置訪問被動模式 這個參數允許啓用/禁用遠程主機連接驗證
                ftp.setRemoteVerificationEnabled(false);
                //每次數據連接之前,ftp client告訴ftp server開通一個端口來傳輸數據
                ftp.enterLocalPassiveMode();
                boolean dir = ftp.changeWorkingDirectory(remoteBaseDir);
                if (dir) {
                FTPFile[] files = null;
                    ftp.setControlEncoding("GBK");
                    files = ftp.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        try {
                            downloadFile(files[i], localBaseDir, remoteBaseDir);
                        } catch (Exception e) {
                            logger.error(e);
                            logger.error("<" + files[i].getName() + ">下載失敗");
                        }
                    }
            } }catch (Exception e) {
                logger.error("下載過程中出現異常",e);
            }
        } else {
            logger.error("鏈接失敗!");
        }

    }

    /**
     * 
     * 下載FTP文件 當你需要下載FTP文件的時候,調用此方法 根據<b>獲取的文件名,本地地址,遠程地址</b>進行下載
     * 
     * @param ftpFile
     * @param relativeLocalPath
     * @param relativeRemotePath
     */
    private static void downloadFile(FTPFile ftpFile, String relativeLocalPath, String relativeRemotePath) {
        System.out.println("下載文件");
        if (ftpFile.isFile()) {
            if (ftpFile.getName().indexOf("?") == -1) {
                OutputStream outputStream = null;
                try {
                    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(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(e);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        File file = new File("E:\\OracleJdbcDemo.java");
        System.out.println(file.getPath());
        FtpUtil.upload(file);// 把文件上傳在ftp上
        FtpUtil.startDown(f, "E:/", "/agentbusi");// 下載ftp文件測試
    }

}
--------------------- 
作者:有夢想的菜菜 
來源:CSDN 
原文:https://blog.csdn.net/forever_yours/article/details/78605205 
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章