使用FTPClient进行文件导入

 

在开发过程中,需要对FTP服务器进行指定文件全部文件扫描

1.创建util类

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.activation.DataHandler;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import com.alibaba.fastjson.JSONObject;
import com.grid.aostar.tgmonitor.queue.UploadData;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FTPListAllFilesUtil {
    public FTPClient ftp;
    public ArrayList<String> arFiles;

    /**
     * 重载构造函数
     *
     * @param isPrintCommmand 是否打印与FTPServer的交互命令
     */
    public FTPListAllFilesUtil(boolean isPrintCommand) {
        ftp = new FTPClient();
        arFiles = new ArrayList<String>();
        if (isPrintCommand) {
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        }
    }

    /**
     * 登陆FTP服务器
     *
     * @param host     FTPServer IP地址
     * @param port     FTPServer 端口
     * @param username FTPServer 登陆用户名
     * @param password FTPServer 登陆密码
     * @return 是否登录成功
     * @throws IOException
     */
    public boolean login(String host, int port, String username, String password) throws IOException {
        this.ftp.setControlEncoding("UTF-8");
        try {
            this.ftp.connect(host, port); // 链接服务器
            if (FTPReply.isPositiveCompletion(this.ftp.getReplyCode())) {
                if (this.ftp.login(username, password)) { // 登录服务器
                    return true;
                } else {
                    log.info("账户或密码错误");
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.info("FTP服务器连接失败,请检查配置ip,端口,及服务器是否正常");
        }
        if (this.ftp.isConnected()) {
            this.ftp.disconnect();
        }
        return false;
    }

    /**
     * 关闭数据链接
     *
     * @throws IOException
     */
    public void disConnection() throws IOException {
        if (this.ftp.isConnected()) {
            this.ftp.disconnect();
        }
    }

    /**
     * 递归遍历目录下面指定后缀的文件,并输出转换后的字符
     *
     * @param pathName 需要遍历的目录,必须以"/"开始和结束
     * @param ext      文件的扩展名
     * @throws IOException
     */
    public ArrayList<List<UploadData>> List(String pathName, String ext) throws IOException {
        ArrayList<List<UploadData>> arrayList = new ArrayList<List<UploadData>>();
        if (pathName.startsWith("/") && pathName.endsWith("/")) {
            // 更换目录到当前目录
            this.ftp.changeWorkingDirectory(pathName);
            FTPFile[] files = this.ftp.listFiles();
            ftp.enterLocalPassiveMode();
            for (FTPFile file : files) {
                if (file.isFile()) {
                    if (file.getName().endsWith(ext)) {
                        // 根据ftp名称下载文件流
                        InputStream inputStream = ftp.retrieveFileStream(toFtpFileName(file.getName()));
//                        if (inputStream != null) {
//                            //根据文件流长度设置byte长度,并转换为string返回
//                            int count = 0; 
//                            while (count == 0) { 
//                                count = inputStream.available(); 
//                            }
//                            byte[] bytes = new byte[count];
//                            if(inputStream.read(bytes) != -1) {
//                                inputStream.read(bytes);
//                                String str = new String(bytes);
//                                arrayList.add(str);
//                                
//                            }
//根据文件内容不同,选择合适的输出方式

                        List<UploadData> lists = new ArrayList<>();
                        try {
                            lists = FTPListAllFilesUtil.parse(inputStream);
                            arrayList.add(lists);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            log.info("类型转换错误");
                            e.printStackTrace();
                        }
                        // 主动消费,防止下次输出文件流为null
                        ftp.getReply();
                        inputStream.close();
                    }
                    arFiles.add(pathName + file.getName());
                }
            }
        }
        return arrayList;
    }

    public static List<UploadData> parse(InputStream in) throws Exception {
        List<UploadData> lists = new ArrayList<UploadData>();
        try {
            SAXBuilder builder = new SAXBuilder();
            Document document = builder.build(in);
            // 获取文档的根节点
            Element rootElement = document.getRootElement();
            String rootId = rootElement.getAttributeValue("id");
            String datatype = rootElement.getAttributeValue("type");
            // 将根节点的所有子节点获取放到一个集合中
            List<Element> list = rootElement.getChildren();

            // 循环遍历所有子节点
            for (Element element : list) {
                UploadData uploadData = new UploadData();
                String key = element.getName();
                List<Element> rdataElements = element.getChildren("rdata"); // 行数据
                List<Map<String, Object>> tempRdataList = new ArrayList<Map<String, Object>>();
                // 获取所有的属性并遍历输出
                for (Element rdataElement : rdataElements) {
                    Map<String, Object> tempRdataMap = new HashMap<String, Object>();
                    tempRdataList.add(tempRdataMap);
                    for (Element rdata : rdataElement.getChildren()) { // 字段
                        tempRdataMap.put(rdata.getName(), rdata.getText());
                    }
                    tempRdataMap.put("hmAddress", rootId);
                }
                if (tempRdataList.size() != 0) {
                    uploadData.setType(key);
                    uploadData.setHmAddress(rootId);
                    uploadData.setDatatype(datatype);
                    uploadData.setDatas(tempRdataList);
                    lists.add(uploadData);
                }
            }
            return lists;
        } catch (Exception e) {
            log.info("传入字节流,转换为JSON对象报错");
            throw e;
        } finally {
            if (in != null) {
                IOUtils.closeQuietly(in);
            }
        }
    }

    private static String toFtpFileName(String fileName) throws IOException {
        return new String(fileName.getBytes("UTF-8"), "ISO8859-1");
    }
}

2.使用

public String ftpListAllFiles() throws Exception {

        /**
         * 建立ftp链接,获取文件数据
         */
        try {
            if (ftplist.login(ip, port, userName, password)) {
                list = ftplist.List("/"//扫描路径), "msg"//文件类型);
            }
        } catch (Exception e) {
            log.info("FTP服务器数据获取失败");
        } finally {
            /**
             * 关闭连接
             */
            ftplist.disConnection();
        }
        

    }

 

posted @ 2020-11-10 16:34  47Knife  阅读(295)  评论(0编辑  收藏  举报