자바 ftp 파일 추출 - 예시

11937 단어 자바 코드
import base.ApplicationTestBase;
import com.yuantiaokj.paycentre.rcbnbspcheck.util.FtpUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import javax.annotation.Resource;
import java.util.Map;

/**
 * ************************************************************
 * Copyright © 2020      Inc.All rights reserved.  *    **
 * ************************************************************
 *
 * @program: financial_eco-environment_cloud
 * @description:
 * @author: cnzz
 * @create: 2020-08-03 10:24
 **/
@Slf4j
public class FtpTest extends ApplicationTestBase {
    @Resource
    FtpUtil ftpUtil;

    @Test
    public void test() {

        //  ftp  
        Map result = ftpUtil.downLoadTableFile("test", "D://");
        log.info("result={}",result);
        //TestCase.assertEquals(true, result.get("result"));
    }
}

 
 
package base;

import com.yuantiaokj.paycentre.rcbnbspcheck.RcbnbspCheckApplication;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

/**
 * ***********************************************************
 * Copyright © 2019      Inc.All rights reserved.  *    *
 * **********************************************************
 *
 * @program: financial_eco-environment_cloud
 * @name: com.yuantiaokj.ApplicationTestBase
 * @author: Mr.Cnzz
 * @create: 2020-01-16 10:24
 * @description:   base
 **/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = RcbnbspCheckApplication.class)
//   Web  ,Junit    ServletContext,               @WebAppConfiguration。
@WebAppConfiguration
public class ApplicationTestBase {
    @Before
    public void init() {
        System.out.println("    -----------------");
    }

    @After
    public void after() {
        System.out.println("    -----------------");
    }
}

위 는 테스트 클래스 이 므 로 스스로 작성 할 수 있 습 니 다.
 
package com.yuantiaokj.paycentre.rcbnbspcheck.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ************************************************************
 * Copyright © 2020      Inc.All rights reserved.  *    **
 * ************************************************************
 *
 * @program: financial_eco-environment_cloud
 * @description: ftp     
 * @author: cnzz
 * @create: 2020-08-03 10:19
 **/
@Slf4j
@Component
public class FtpUtil {
    /**
     *       
     */
    public static final String DIR_NOT_EXIST = "      ";

    /**
     * "        
     */
    public static final String DIR_CONTAINS_NO_FILE = "        ";

    /**
     * FTP  
     **/
    @Value("${ftp.host}")
    private String ftpAddress;
    /**
     * FTP  
     **/
    @Value("${ftp.port}")
    private int ftpPort = 521;
    /**
     * FTP   
     **/
    @Value("${ftp.username}")
    private String ftpUsername;
    /**
     * FTP  
     **/
    @Value("${ftp.password}")
    private String ftpPassword;
    /**
     * FTP    
     **/
    @Value("${ftp.basepath}")
    private String basePath;

    /**
     *       
     **/
    private static String localCharset = "GBK";

    /**
     * FTP    ,        iso-8859-1
     **/
    private static String serverCharset = "ISO-8859-1";

    /**
     * UTF-8    
     **/
    private static final String CHARSET_UTF8 = "UTF-8";

    /**
     * OPTS UTF8     
     **/
    private static final String OPTS_UTF8 = "OPTS UTF8";

    /**
     *        4M
     **/
    private static final int BUFFER_SIZE = 1024 * 1024 * 4;

    /**
     * FTPClient  
     **/
    private static FTPClient ftpClient = null;


    /**
     *              
     *
     * @param ftpPath  FTP         ,  :test/123
     * @param savePath           ,  :D:/test
     * @return     true,    false
     */
    public boolean downloadFiles(String ftpPath, String savePath) {
        //   
        login(ftpAddress, ftpPort, ftpUsername, ftpPassword);
        if (ftpClient != null) {
            try {
                String path = changeEncoding(basePath + ftpPath);
                //          
                if (!ftpClient.changeWorkingDirectory(path)) {
                    log.error(basePath + ftpPath + DIR_NOT_EXIST);
                    return Boolean.FALSE;
                }
                ftpClient.enterLocalPassiveMode();  //       ,           
                String[] fs = ftpClient.listNames();
                //            
                if (fs == null || fs.length == 0) {
                    log.error(basePath + ftpPath + DIR_CONTAINS_NO_FILE);
                    return Boolean.FALSE;
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    File file = new File(savePath + '/' + ftpName);
                    try (OutputStream os = new FileOutputStream(file)) {
                        ftpClient.retrieveFile(ff, os);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            } catch (IOException e) {
                log.error("      ", e);
            } finally {
                closeConnect();
            }
        }
        return Boolean.TRUE;
    }

    /**
     *   FTP   
     *
     * @param address    , :127.0.0.1
     * @param port       , :21
     * @param username    , :root
     * @param password   , :root
     */
    private void login(String address, int port, String username, String password) {
        log.info("ssh  |address={},port={},username={},password={}", address, port, username, password);
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(address, port);
            ftpClient.login(username, password);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //       
            ftpClient.setBufferSize(BUFFER_SIZE);
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                closeConnect();
                log.error("FTP       ");
            }
        } catch (Exception e) {
            log.error("FTP    ", e);
        }
    }


    /**
     * FTP         
     *
     * @param ftpPath FTP     
     * @return String
     */
    private static String changeEncoding(String ftpPath) {
        String directory = null;
        try {
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
                localCharset = CHARSET_UTF8;
            }
            directory = new String(ftpPath.getBytes(localCharset), serverCharset);
        } catch (Exception e) {
            log.error("        ", e);
        }
        return directory;
    }

    /**
     *   FTP  
     */
    private void closeConnect() {
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                log.error("  FTP    ", e);
            }
        }
    }

    /**
     *                
     *
     * @param ftpPath  FTP         ,  :test/123
     * @param fileName        ,  :test.txt
     * @return     true,    false
     */
    public boolean checkFileInFtp(String ftpPath, String fileName) {
        //   
        login(ftpAddress, ftpPort, ftpUsername, ftpPassword);
        if (ftpClient != null) {
            try {
                String path = changeEncoding(basePath + ftpPath);
                //          
                if (!ftpClient.changeWorkingDirectory(path)) {
                    log.error(basePath + ftpPath + DIR_NOT_EXIST);
                    return Boolean.FALSE;
                }
                ftpClient.enterLocalPassiveMode();  //       ,           
                String[] fs = ftpClient.listNames();
                //            
                if (fs == null || fs.length == 0) {
                    log.error(basePath + ftpPath + DIR_CONTAINS_NO_FILE);
                    return Boolean.FALSE;
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    if (ftpName.equals(fileName)) {
                        return Boolean.TRUE;
                    }
                }
            } catch (IOException e) {
                log.error("    ", e);
            } finally {
                closeConnect();
            }
        }
        return Boolean.TRUE;
    }

    /**
     *                           
     *
     * @param ftpPath  FTP         ,  :test/123
     * @param savePath           ,  :D:/test
     * @return     true,    false
     */
    public Map downLoadTableFile(String ftpPath, String savePath) {
        //   
        login(ftpAddress, ftpPort, ftpUsername, ftpPassword);
        Map resultMap = new HashMap<>();
        if (ftpClient != null) {
            try {
                String path = changeEncoding(basePath + "/" + ftpPath);
                //          
                if (!ftpClient.changeWorkingDirectory(path)) {
                    log.error(basePath + "/" + ftpPath + DIR_NOT_EXIST);
                    resultMap.put("result", false);
                    return resultMap;
                }
                ftpClient.enterLocalPassiveMode();  //       ,           
                String[] fs = ftpClient.listNames();
                //            
                if (fs == null || fs.length == 0) {
                    log.error(basePath + "/" + ftpPath + DIR_CONTAINS_NO_FILE);
                    resultMap.put("result", false);
                    return resultMap;
                }
                List tableFileNameList = new ArrayList<>();
                //         
                String tableDirName = savePath + "/" + ftpPath;
                File tableDirs = new File(tableDirName);
                if (!tableDirs.exists()) {
                    tableDirs.mkdirs();
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    File file = new File(tableDirName + "/" + ftpName);
                    //          
                    tableFileNameList.add(tableDirName + "/" + ftpName);
                    try (OutputStream os = new FileOutputStream(file)) {
                        ftpClient.retrieveFile(ff, os);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
                resultMap.put("fileNameList", tableFileNameList);
                resultMap.put("result", true);
                return resultMap;
            } catch (IOException e) {
                log.error("      ", e);
            } finally {
                closeConnect();
            }
        }
        resultMap.put("result", false);
        return resultMap;
    }
}

좋은 웹페이지 즐겨찾기