FTP文件的使用

FTP操作的工具类:

package com.tl.task.util;

import com.tl.task.pojo.TaskList;
import org.apache.commons.net.ftp.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class FtpUtils {
    private String Control_Encoding = "UTF-8";

    private FTPClient client = null;

    private String host = "";
    private int port = 21;
    private String user = "";
    private String password = "";
    private String ftpPath = "/";

    @SuppressWarnings("unused")
    private FtpUtils() {
    }

    public FtpUtils(String host, int port, String user, String pwd) {
        this.host = host;
        this.port = port;
        this.user = user;
        this.password = pwd;
    }

    /**
     * 连接FTP Server
     *
     * @throws IOException
     */
    public static final String ANONYMOUS_USER = "anonymous";

    public String connect() throws Exception {
        if (client == null) {
            client = new FTPClient();
        }
        // 已经连接
        if (client.isConnected()) {
            return "已经连接,无法连接";
        }

        // 编码
        client.setControlEncoding(Control_Encoding);

        try {
            // 连接FTP Server
            client.connect(this.host, this.port);
            // 登陆
            if (this.user == null || "".equals(this.user)) {
                // 使用匿名登陆
                client.login(ANONYMOUS_USER, ANONYMOUS_USER);
            } else {
                client.login(this.user, this.password);
            }
            // 设置文件格式
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 获取FTP Server 应答
            int reply = client.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                client.disconnect();
                throw new Exception("connection FTP fail!");
            }

            FTPClientConfig config = new FTPClientConfig(client.getSystemType().split(" ")[0]);
            config.setServerLanguageCode("zh");
            client.configure(config);
            // 使用被动模式设为默认
            client.enterLocalPassiveMode();
            // 二进制文件支持
            client.setFileType(FTP.BINARY_FILE_TYPE);
            // 设置模式
            client.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            return "登陆成功";

        } catch (IOException e) {
            throw new Exception("connection FTP fail! " + e);
        }
    }
    //根据路径获取文件中的文件数组

    public List<FTPFile> list() {
        List<FTPFile> list = null;
        try {
            FTPFile ff[] = client.listFiles(ftpPath);
            if (ff != null && ff.length > 0) {
                list = new ArrayList<FTPFile>(ff.length);
                Collections.addAll(list, ff);
            } else {
                list = new ArrayList<FTPFile>(0);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public boolean upload(File localFile) {
        return this.upload(localFile);
    }

    public String getControl_Encoding() {
        return Control_Encoding;
    }

    public void setControl_Encoding(String control_Encoding) {
        Control_Encoding = control_Encoding;
    }

    public FTPClient getClient() {
        return client;
    }

    public void setClient(FTPClient client) {
        this.client = client;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFtpPath() {
        return ftpPath;
    }

    public void setFtpPath(String ftpPath) {
        this.ftpPath = ftpPath;
    }

    public static String getAnonymousUser() {
        return ANONYMOUS_USER;
    }


    public  String switchDirectory(String path) {
        System.out.println(path);
        try {
            if (path != null && !"".equals(path)) {
                boolean ok = client.changeWorkingDirectory(path);
                if (ok) {
                    this.ftpPath = path;
                }
            }
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "NOT FOUND";
    }
    //下载FTP文件
    public boolean download(String ftpFileName, String savePath) {
        boolean flag = false;

        File dir = new File(savePath);

        if (!dir.exists()) {
            dir.mkdirs();
        }

        FileOutputStream fos = null;
        try {
            String saveFile = dir.getAbsolutePath() + File.separator + ftpFileName;
            fos = new FileOutputStream(new File(saveFile));
            boolean ok = client.retrieveFile(ftpFileName, fos);
            if (ok) {
                flag = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }
//    删除FTP文件
    public boolean deleteFile(String path) {
        boolean flag = false;
        try {
            flag = client.deleteFile(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }
//读取xml文件中的内容
    public static   List<TaskList> getXml(String pathname){
        System.out.println(pathname);
        Integer falg2 = 2;
        Integer flag = 1;
        List<TaskList> xmlList = new LinkedList<>();
        Element element = null;
        // 可以使用绝对路劲
        File f = new File(pathname);

        // documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件)
        DocumentBuilder db = null;
        DocumentBuilderFactory dbf = null;
        try {
            // 返回documentBuilderFactory对象
            dbf = DocumentBuilderFactory.newInstance();
            // 返回db对象用documentBuilderFatory对象获得返回documentBuildr对象
            db = dbf.newDocumentBuilder();

            // 得到一个DOM并返回给document对象
            Document dt = db.parse(f);
            // 得到一个elment根元素
            element = dt.getDocumentElement();
            // 获得根节点
            if (!"TPLAN".equals(element.getNodeName())){
                System.out.println("XML文件内容有问题");
            }

            // 获得根元素下的子节点
            NodeList childNodes = element.getChildNodes();
//            TaskList taskList = new TaskList();
            // 遍历这些子节点
            for (int i = 0; i < childNodes.getLength(); i++) {
                TaskList taskList = new TaskList();
                // 获得每个对应位置i的结点
                Node node1 = childNodes.item(i);
                    // 如果节点的名称为"Account",则输出Account元素属性type
                    // 获得<Accounts>下的节点
                    NodeList nodeDetail = node1.getChildNodes();
                    // 遍历<Accounts>下的节点
                    for (int j = 0; j < nodeDetail.getLength(); j++) {
                        // 获得<Accounts>元素每一个节点
                        Node detail = nodeDetail.item(j);

//                        System.out.print(detail.getNodeName().replace("#text",""));
//                        System.out.print(detail.getTextContent().trim());
                        if (detail.getNodeName().equals("STATION")){
                            taskList.setStation(detail.getTextContent());
                        }
                        if (detail.getNodeName().equals("CODE")){
                            taskList.setWxbh(detail.getTextContent());
                        }
                        if (detail.getNodeName().equals("TRACE")){
                            NodeList childNodes1 = detail.getChildNodes();
                            for (int k = 0; k <childNodes1.getLength() ; k++) {
                                Node item = childNodes1.item(k);
                                if (item.getNodeName().equals("TM") ){
                                    taskList.setTm(item.getTextContent());
                                }

                    }
                    if (i%2==1){
                        System.out.println(taskList);
                        xmlList.add(taskList);
                    }

                }
            return xmlList;

        }

        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值