`

commons-net包的FTP功能

阅读更多
package com.sinomos.rpt.bean;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPConnectionClosedException;

/** *//**
* @applicability 10.1.10.19 10.1.10.20
*/
public class uFtp ...{
    
    private FTPClient ftpClient = null;
    
    //private OutputStream outSteam = null;
    
    //ftp服务器地址
    private String hostName;
    
    //ftp服务器默认端口
    public static int defaultport = 21;
        
    //登录名
    private String userName;
        
    //登录密码   
    private String password;
        
    //需要访问的远程目录
    private String remoteDir;
    
    /** *//**
     * @param hostName    主机地址
     * @param port        端口号
     * @param userName    用户名
     * @param password    密码
     * @param remoteDir    默认工作目录
     * @param is_zhTimeZone    是否是中文FTP Server端
     * @return
     */
    public uFtp(String hostName,int port,String userName,String password,String remoteDir,boolean is_zhTimeZone) ...{
        this.hostName=hostName;
        this.userName=userName;
        this.password=password;
        this.remoteDir=remoteDir==null?"":remoteDir;        
        this.ftpClient = new FTPClient();
        if(is_zhTimeZone) ...{
            this.ftpClient.configure(uFtp.Config());
            this.ftpClient.setControlEncoding("GBK");
        }
        this.login();
        this.changeDir(this.remoteDir);
        this.setFileType(FTPClient.ASCII_FILE_TYPE);
        //this.changeDir(this.remoteDir);
        ftpClient.setDefaultPort(port);
    }    
    
    /** *//**
     * 登录FTP服务器
     */
    public void login() ...{
        try ...{
            ftpClient.connect(this.hostName);            
            ftpClient.login(this.userName, this.password);
        } catch (FTPConnectionClosedException e) ...{
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) ...{
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("连接到ftp服务器:" + this.hostName + " 成功..开始登录");
    }
    //FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
    
    private static FTPClientConfig Config() ...{
        FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
        conf.setRecentDateFormatStr("MM月dd日 HH:mm");
        //conf.setRecentDateFormatStr("(YYYY年)?MM月dd日( HH:mm)?");
        return conf;
    }
    /** *//**
     * 变更工作目录
     * @param remoteDir--目录路径 
     */
    public void changeDir(String remoteDir) ...{
        try ...{
            this.remoteDir = remoteDir;
            ftpClient.changeWorkingDirectory(remoteDir);
        } catch (IOException e) ...{
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("变更工作目录为:"+remoteDir);
    }
    
    /** *//**
     * 返回上一级目录(父目录)
     */
    public void ToParentDir() ...{
        try ...{
            ftpClient.changeToParentDirectory();
        } catch (IOException e) ...{
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /** *//**
     * 列出当前工作目录下所有文件
     */
    public String[] ListAllFiles() ...{
        String[] names=this.ListFiles("*");
        return this.sort(names);
    }
    
    /** *//**
     * 列出指定工作目录下的匹配文件
     * @param dir exp: /cim/
     * @param file_regEx 通配符为*
     */
    public String[] ListAllFiles(String dir,String file_regEx) ...{
        String[] names=this.ListFiles(dir+file_regEx);
        return this.sort(names);
    }
    
    /** *//**
     * 列出匹配文件
     * @param file_regEx 匹配字符,通配符为*
     */
    public String[] ListFiles(String file_regEx) ...{
        try ...{
            /**//*
            FTPFile[] remoteFiles = ftpClient.listFiles(file_regEx);
            //System.out.println(remoteFiles.length);
            String[] name = new String[remoteFiles.length];
            if(remoteFiles != null) {
                for(int i=0;i<remoteFiles.length;i++) {
                    if(remoteFiles[i] == null)
                        name[i] = "";
                    else if(remoteFiles[i].getName()==null||remoteFiles[i].getName().equals(".")||remoteFiles[i].getName().equals("..")) {
                        name[i] = "";
                    }
                    else name[i] = remoteFiles[i].getName();
                    System.out.println(name[i]);
                }
            }
            */
            String[] name = ftpClient.listNames(file_regEx);
            if(name==null) 
                return new String[0];
            return this.sort(name);
        } catch (IOException e) ...{
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new String[0];
    }
    
    public void Lists(String reg) ...{
        try ...{
            String[] a=ftpClient.listNames(reg);
            for(String b:a) ...{
                System.out.println(b);
            }
        } catch (IOException e) ...{
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /** *//**
     * 设置传输文件的类型[文本文件或者二进制文件]
     * @param fileType--BINARY_FILE_TYPE,ASCII_FILE_TYPE 
     */
    public void setFileType(int fileType)...{
        try...{
            ftpClient.setFileType(fileType);
        }catch(IOException e)...{
            e.printStackTrace();
        }
    }
    
    /** *//**
     * 上传文件
     * @param localFilePath--本地文件路径+文件名
     * @param newFileName--新的文件名
     */
    public void uploadFile(String localFilePath,String newFileName)...{
        //上传文件
        BufferedInputStream buffIn=null;
        try...{
            buffIn=new BufferedInputStream(new FileInputStream(localFilePath));
            ftpClient.storeFile(newFileName, buffIn);
        }catch(Exception e)...{
            e.printStackTrace();
        }finally...{
            try...{
                if(buffIn!=null)
                    buffIn.close();
            }catch(Exception e)...{
                e.printStackTrace();
            }
        }
    }
    
    /** *//**
     * 下载文件(单个)
     * @param remoteFileName --服务器上的文件名
     * @param localFileName--本地文件名
     */
    public String downloadFile(String remoteFileName,String localFileName)...{
        BufferedOutputStream buffOut=null;
        try...{
            buffOut=new BufferedOutputStream(new FileOutputStream(localFileName));
            ftpClient.retrieveFile(remoteFileName, buffOut);
        }catch(Exception e)...{
            e.printStackTrace();
            return "";
        }finally...{
            try...{
                if(buffOut!=null)
                    buffOut.close();
            }catch(Exception e)...{
                e.printStackTrace();
            }
        }
        return localFileName;
    }
    
    /** *//**
     * 关闭FTP连接
     */
    public void close() ...{
        try...{
            if(ftpClient!=null)...{
                ftpClient.logout();
                ftpClient.disconnect();
            }
        }catch (Exception e)...{
            e.printStackTrace();
        }
    }
    
    /** *//**
     * 冒泡排序字符串(从大到小)
     */
    public String[] sort(String[] str_Array) ...{
        if(str_Array==null) ...{
            throw new NullPointerException("The str_Array can not be null!");
        }
        String tmp = "";
        for(int i=0;i<str_Array.length;i++) ...{
            for(int j=0;j<str_Array.length-i-1;j++) ...{
                if(str_Array[j].compareTo(str_Array[j+1])<0) ...{
                    tmp = str_Array[j];
                    str_Array[j] = str_Array[j + 1];
                    str_Array[j + 1] = tmp;
                }
            }
        }
        return str_Array;
    }

    /** *//**
     * @param args
     */
    public static void main(String[] args) ...{
        // TODO Auto-generated method stub
        
        //String[] files = null;
        uFtp ftp = new uFtp("10.1.10.19",uFtp.defaultport,"eda","sinomos","/tyne_home/wat/db/",true);
        //uftp.ListFiles();
        //ftp.changeDir("/tyne_home/wat/db/");
        //String[] s = ftp.ListFiles("*SN_141*.wdf");
        //System.out.println(s.length);
        ftp.Lists("SN_141.wdf");
        //ftp.downloadFile("SN_141.wdf", "Data/SN_141.wdf");
        /**//*
        System.out.println("==========================");
        for(int i=0;i<files.length;i++) {
            System.out.println("files["+i+"]:"+files[i]);
        }*/
        //uftp.uploadFile("D:/TestFile/temp.xml", "temp.xml");        
    }
}

 

如果用的是中文的FTP服务器端,则要在Project中重载
org.apache.commons.net.ftp.parser.UnixFTPEntryParser类

/**//*
* Copyright 2001-2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.ftp.parser;

import java.text.ParseException;

import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;

/** *//**
* Implementation FTPFileEntryParser and FTPFileListParser for standard Unix
* Systems.
*
* This class is based on the logic of Daniel Savarese's DefaultFTPListParser,
* but adapted to use regular expressions and to fit the new FTPFileEntryParser
* interface.
*
* @version $Id: UnixFTPEntryParser.java,v 1.1 2007/01/18 04:20:59 others Exp $
* @see org.apache.commons.net.ftp.FTPFileEntryParser FTPFileEntryParser (for
*      usage instructions)
*/
public class UnixFTPEntryParser extends ConfigurableFTPFileEntryParserImpl ...{
    /** *//**
     * months abbreviations looked for by this parser. Also used to determine
     * which month is matched by the parser
     */
    @SuppressWarnings("unused")
    private static final String DEFAULT_MONTHS = "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)";

    static final String DEFAULT_DATE_FORMAT = "MMM d yyyy"; // Nov 9 2001

    static final String DEFAULT_RECENT_DATE_FORMAT = "MMM d HH:mm"; // Nov 9

    // 20:06

    static final String NUMERIC_DATE_FORMAT = "yyyy-MM-dd HH:mm"; // 2001-11-09

    // 20:06

    /** *//**
     * Some Linux distributions are now shipping an FTP server which formats
     * file listing dates in an all-numeric format:
     * <code>"yyyy-MM-dd HH:mm</code>. This is a very welcome development,
     * and hopefully it will soon become the standard. However, since it is so
     * new, for now, and possibly forever, we merely accomodate it, but do not
     * make it the default.
     * <p>
     * For now end users may specify this format only via
     * <code>UnixFTPEntryParser(FTPClientConfig)</code>. Steve Cohen -
     * 2005-04-17
     */
    public static final FTPClientConfig NUMERIC_DATE_CONFIG = new FTPClientConfig(
            FTPClientConfig.SYST_UNIX, NUMERIC_DATE_FORMAT, null, null, null,
            null);

    /** *//**
     * this is the regular expression used by this parser.
     *
     * Permissions: r the file is readable w the file is writable x the file is
     * executable - the indicated permission is not granted L mandatory locking
     * occurs during access (the set-group-ID bit is on and the group execution
     * bit is off) s the set-user-ID or set-group-ID bit is on, and the
     * corresponding user or group execution bit is also on S undefined
     * bit-state (the set-user-ID bit is on and the user execution bit is off) t
     * the 1000 (octal) bit, or sticky bit, is on [see chmod(1)], and execution
     * is on T the 1000 bit is turned on, and execution is off (undefined bit-
     * state)
     */
    private static final String REGEX = "([bcdlfmpSs-])"
            + "(((r|-)(w|-)([xsStTL-]))((r|-)(w|-)([xsStTL-]))((r|-)(w|-)([xsStTL-])))\+?\s+"
            + "(\d+)\s+" + "(\S+)\s+" + "(?:(\S+)\s+)?" + "(\d+)\s+"

            /**//*
             * numeric or standard format date
             */
            // + "((?:\d+[-/]\d+[-/]\d+)|(?:\S+\s+\S+))\s+"
            // 2007/01/16 Yyong modify to match chinese date format
            + "((?:\d+[-/]\d+[-/]\d+)|(?:\S+\s+\S+)|(?:\d+月\d+日))\s+"

            /**//*
             * year (for non-recent standard format) or time (for numeric or
             * recent standard format
             */
            + "(\d+(?::\d+)?)\s+"

            + "(\S*)(\s*.*)";

    /** *//**
     * The default constructor for a UnixFTPEntryParser object.
     *
     * @exception IllegalArgumentException
     *                Thrown if the regular expression is unparseable. Should
     *                not be seen under normal conditions. It it is seen, this
     *                is a sign that <code>REGEX</code> is not a valid regular
     *                expression.
     */
    public UnixFTPEntryParser() ...{
        this(null);
    }

    /** *//**
     * This constructor allows the creation of a UnixFTPEntryParser object with
     * something other than the default configuration.
     *
     * @param config
     *            The {@link FTPClientConfig configuration} object used to
     *            configure this parser.
     * @exception IllegalArgumentException
     *                Thrown if the regular expression is unparseable. Should
     *                not be seen under normal conditions. It it is seen, this
     *                is a sign that <code>REGEX</code> is not a valid regular
     *                expression.
     * @since 1.4
     */
    public UnixFTPEntryParser(FTPClientConfig config) ...{
        super(REGEX);
        configure(config);
    }

    /** *//**
     * Parses a line of a unix (standard) FTP server file listing and converts
     * it into a usable format in the form of an <code> FTPFile </code>
     * instance. If the file listing line doesn't describe a file,
     * <code> null </code> is returned, otherwise a <code> FTPFile </code>
     * instance representing the files in the directory is returned.
     * <p>
     *
     * @param entry
     *            A line of text from the file listing
     * @return An FTPFile instance corresponding to the supplied entry
     */
    public FTPFile parseFTPEntry(String entry) ...{
        FTPFile file = new FTPFile();
        file.setRawListing(entry);
        int type;
        boolean isDevice = false;

        if (matches(entry)) ...{
            String typeStr = group(1);
            String hardLinkCount = group(15);
            String usr = group(16);
            String grp = group(17);
            String filesize = group(18);
            String datestr = group(19) + " " + group(20);
            String name = group(21);
            String endtoken = group(22);

            try ...{
                file.setTimestamp(super.parseTimestamp(datestr));
            } catch (ParseException e) ...{
                return null; // this is a parsing failure too.
            }

            // bcdlfmpSs-
            switch (typeStr.charAt(0)) ...{
            case 'd':
                type = FTPFile.DIRECTORY_TYPE;
                break;
            case 'l':
                type = FTPFile.SYMBOLIC_LINK_TYPE;
                break;
            case 'b':
            case 'c':
                isDevice = true;
                // break; - fall through
            case 'f':
            case '-':
                type = FTPFile.FILE_TYPE;
                break;
            default:
                type = FTPFile.UNKNOWN_TYPE;
            }

            file.setType(type);

            int g = 4;
            for (int access = 0; access < 3; access++, g += 4) ...{
                // Use != '-' to avoid having to check for suid and sticky bits
                file.setPermission(access, FTPFile.READ_PERMISSION, (!group(g)
                        .equals("-")));
                file.setPermission(access, FTPFile.WRITE_PERMISSION, (!group(
                        g + 1).equals("-")));

                String execPerm = group(g + 2);
                if (!execPerm.equals("-")
                        && !Character.isUpperCase(execPerm.charAt(0))) ...{
                    file
                            .setPermission(access, FTPFile.EXECUTE_PERMISSION,
                                    true);
                } else ...{
                    file.setPermission(access, FTPFile.EXECUTE_PERMISSION,
                            false);
                }
            }

            if (!isDevice) ...{
                try ...{
                    file.setHardLinkCount(Integer.parseInt(hardLinkCount));
                } catch (NumberFormatException e) ...{
                    // intentionally do nothing
                }
            }

            file.setUser(usr);
            file.setGroup(grp);

            try ...{
                file.setSize(Long.parseLong(filesize));
            } catch (NumberFormatException e) ...{
                // intentionally do nothing
            }

            if (null == endtoken) ...{
                file.setName(name);
            } else ...{
                // oddball cases like symbolic links, file names
                // with spaces in them.
                name += endtoken;
                if (type == FTPFile.SYMBOLIC_LINK_TYPE) ...{

                    int end = name.indexOf(" -> ");
                    // Give up if no link indicator is present
                    if (end == -1) ...{
                        file.setName(name);
                    } else ...{
                        file.setName(name.substring(0, end));
                        file.setLink(name.substring(end + 4));
                    }

                } else ...{
                    file.setName(name);
                }
            }
            return file;
        }
        return null;
    }

    /** *//**
     * Defines a default configuration to be used when this class is
     * instantiated without a {@link FTPClientConfig FTPClientConfig}
     * parameter being specified.
     *
     * @return the default configuration for this parser.
     */
    protected FTPClientConfig getDefaultConfiguration() ...{
        return new FTPClientConfig(FTPClientConfig.SYST_UNIX,
                DEFAULT_DATE_FORMAT, DEFAULT_RECENT_DATE_FORMAT, null, null,
                null);
    }
}

分享到:
评论

相关推荐

    commons-net-ftp-2.0.jar.zip

    在`commons-net-ftp-2.0.jar`中,你可以找到一系列预定义的类和接口,如`FTPClient`、`FTPFile`、`FTPSSLConnection`等,它们为FTP操作提供了丰富的功能。`FTPClient`是核心类,负责建立和管理与FTP服务器的连接,...

    commons-net-jar包.zip

    在这个"commons-net-jar包.zip"压缩包中,包含了两个版本的Apache Commons Net库:commons-net-3.3.jar和commons-net-3.4.jar。这两个版本虽然相差不大,但每个新版本通常会带来一些改进和修复,使得开发者能够更...

    Android 利用commons-net-3.3实现ftp上传下载Demo

    implementation 'org.apache.commons:commons-net:3.6' // 使用最新版本替代3.3 } ``` 然后,我们需要创建一个FTP客户端实例并配置连接参数,如服务器地址、端口号、用户名和密码。以下是一个简单的FTP连接示例: ...

    commons-net-3.6

    3. **commons-net-examples-3.6.jar**:包含了一些示例代码,演示了如何使用Apache Commons Net库的各种功能。这些例子是学习和快速上手的良好起点,可以帮助开发者快速理解和应用库中的函数。 此外,压缩包中还有...

    commons-net-3.6 jar包.zip

    在`commons-net-3.6.jar`这个版本中,我们主要关注FTP功能,因为这是该库最广泛使用的部分。 FTP支持是Apache Commons Net的核心功能之一。它提供了全面的FTP客户端实现,包括连接管理、文件上传、下载、列表操作、...

    commons-net-3.6.jar

    在这个版本中,我们聚焦于`commons-net-3.6.jar`,它提供了丰富的API和工具,使开发者能够方便地进行FTP文件的上传、下载以及读写操作。这个库不仅简化了FTP操作,还为开发者提供了深入理解其内部工作原理的机会,...

    commons-net-3.1.jar,3.3,3.6版本

    这个库在不同的版本中提供了各种功能的增强和优化,比如`commons-net-3.1.jar`, `commons-net-3.3.jar`, 和 `commons-net-3.6.jar`。下面将详细阐述这些版本中涉及的主要知识点: 1. **FTP(文件传输协议)支持**:...

    apache的FTP包commons-net-1.4.1.jar,jakarta-oro-2.0.8.jar

    Apache的FTP库是Java开发中一个非常实用的工具,它主要包含了两个核心的JAR包:`commons-net-1.4.1.jar`和`jakarta-oro-2.0.8.jar`。这两个包提供了丰富的功能,允许开发者在Java应用中实现FTP(文件传输协议)的...

    commons-net-ftp-2.0.rar

    这个库,如"commons-net-ftp-2.0.rar"所示,包含了一系列的JAR文件,使得开发者能够轻松地构建FTP客户端应用。 FTP(File Transfer Protocol)是一种用于在Internet上可靠地传输文件的协议。Apache Commons Net库为...

    commons-net-3.3-3.4-3.5-3.6.zip

    在这个压缩包"commons-net-3.3-3.4-3.5-3.6.zip"中,包含了Apache Commons Net库的四个不同版本:3.3、3.4、3.5和3.6,这使得开发者可以根据项目的具体需求选择适合的版本。 Apache Commons Net库是Apache软件基金...

    commons-net-1.4.1.jar

    在这个版本中,我们聚焦于"commons-net-1.4.1.jar",这是一个专注于FTP(文件传输协议)功能的组件。该库为Java开发者提供了丰富的API,以便在他们的应用程序中轻松地集成FTP服务。 FTP是互联网上最古老的协议之一...

    commons-net-3.3.jar

    总结,Apache Commons Net 3.3为Java开发者提供了强大且全面的网络协议工具,尤其是FTP功能,使得FTP编程变得简单高效。无论你是新手还是经验丰富的开发者,这个库都将是你的得力助手,帮助你在网络通信领域游刃有余...

    jar包-commons-net-3.3.jar

    **标题解析:**"jar包-commons-net-3.3.jar" 这个标题表明我们正在讨论的是一个Java Archive(JAR)文件,名为"commons-net-3.3.jar"。JAR文件是Java平台上的标准归档格式,通常用于打包类库、资源文件以及应用程序...

    commons-net-3.2.jar

    在本篇文章中,我们将深入探讨"commons-net-3.2.jar"这一版本的功能、特性以及如何在实际项目中应用。 一、概述 Apache Commons Net 3.2是该库的一个稳定版本,它提供了一系列接口和类,以支持各种网络协议的操作...

    commons-net-3.2

    描述中提到,这个压缩包包含了Apache Commons Net 3.2的jar包,即`commons-net-3.2.jar`,这是运行时需要的库文件,开发者可以直接将其添加到项目类路径中来利用其网络功能。另外,还提供了`commons-...

    commons-net-1.4.1.jar功能实现demo

    `commons-net`库提供了`FTPClient`类,它是实现FTP功能的核心,可以执行登录、改变目录、列出目录内容、上传文件、下载文件等操作。例如,使用`FTPClient.connect()`方法可以建立到FTP服务器的连接,`FTPClient....

    commons-net-3.3源码包

    在这个"commons-net-3.3源码包"中,我们可以深入理解其实现细节,对其进行定制和扩展,这对于开发人员来说非常有用。下面我们将详细探讨此源码包中的关键知识点。 1. **FTP协议实现**: Commons Net库的核心功能之...

    com.jcraft.jsch_0.1.31.jar和commons-net-3.2.jar

    标题中的"com.jcraft.jsch_0.1.31.jar"和"commons-net-3.2.jar"是两个在Java开发中常用的库文件,它们主要用于处理不同的网络通信任务。让我们详细了解一下这两个库以及它们在实际开发中的作用。 首先,`...

    利用commons-net包实现ftp上传下载例子

    标题中的“利用commons-net包实现ftp上传下载例子”是指通过Apache Commons Net库来实现FTP(File Transfer Protocol)的上传和下载功能。Apache Commons Net是Apache软件基金会开发的一个Java库,它提供了多种网络...

    commons-net-2.2.jar_JAR包源码

    《深入解析`commons-net-2.2.jar`:FTP文件上传功能实现》 在Java开发中,Apache Commons Net库是一个非常重要的工具集,它提供了多种网络协议的实现,包括FTP(文件传输协议)。`commons-net-2.2.jar`是这个库的一...

Global site tag (gtag.js) - Google Analytics