`
yongpeng
  • 浏览: 29352 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

使用 apache的 common FTPClient 操作ftp

阅读更多

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.SocketException; 
import java.util.ArrayList; 
import java.util.Date; 
import java.util.List; 
import org.apache.commons.net.ftp.FTP; 
import org.apache.commons.net.ftp.FTPClient; 
import org.apache.commons.net.ftp.FTPFile; 
 
public class FtpUtil { 
    private FTPClient ftpClient; 
    public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE
    public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE
     
    // path should not the path from root index 
    // or some FTP server would go to root as '/'. 
    public void connectServer(FtpConfig ftpConfig) throws SocketException, 
            IOException { 
        String server = ftpConfig.getServer(); 
        int port = ftpConfig.getPort(); 
        String user = ftpConfig.getUsername(); 
        String password = ftpConfig.getPassword(); 
        String location = ftpConfig.getLocation(); 
        connectServer(server, port, user, password, location); 
    } 
     
     
    public void connectServer(String server, int port, String user, 
            String password, String path) throws SocketException, IOException { 
        ftpClient = new FTPClient(); 
        ftpClient.connect(server, port); 
        System.out.println("Connected to " + server + "."); 
        System.out.println(ftpClient.getReplyCode()); 
        ftpClient.login(user, password); 
        // Path is the sub-path of the FTP path 
        if (path.length() != 0) { 
            ftpClient.changeWorkingDirectory(path); 
        } 
    } 
    //FTP.BINARY_FILE_TYPE | FTP.ASCII_FILE_TYPE 
    // Set transform type 
    public void setFileType(int fileType) throws IOException { 
        ftpClient.setFileType(fileType); 
    } 
 
    public void closeServer() throws IOException { 
        if (ftpClient.isConnected()) { 
            ftpClient.disconnect(); 
        } 
    } 
    //======================================================================= 
    //==         About directory       ===== 
    // The following method using relative path better. 
    //======================================================================= 
     
    public boolean changeDirectory(String path) throws IOException { 
        return ftpClient.changeWorkingDirectory(path); 
    } 
    public boolean createDirectory(String pathName) throws IOException { 
        return ftpClient.makeDirectory(pathName); 
    } 
    public boolean removeDirectory(String path) throws IOException { 
        return ftpClient.removeDirectory(path); 
    } 
     
    // delete all subDirectory and files. 
    public boolean removeDirectory(String path, boolean isAll) 
            throws IOException { 
         
        if (!isAll) { 
            return removeDirectory(path); 
        } 
 
        FTPFile[] ftpFileArr = ftpClient.listFiles(path); 
        if (ftpFileArr == null || ftpFileArr.length == 0) { 
            return removeDirectory(path); 
        } 
        //  
        for (FTPFile ftpFile : ftpFileArr) { 
            String name = ftpFile.getName(); 
            if (ftpFile.isDirectory()) { 
        System.out.println("* [sD]Delete subPath ["+path + "/" + name+"]");              
                removeDirectory(path + "/" + name, true); 
            } else if (ftpFile.isFile()) { 
        System.out.println("* [sF]Delete file ["+path + "/" + name+"]");                         
                deleteFile(path + "/" + name); 
            } else if (ftpFile.isSymbolicLink()) { 
 
            } else if (ftpFile.isUnknown()) { 
 
            } 
        } 
        return ftpClient.removeDirectory(path); 
    } 
     
    // Check the path is exist; exist return true, else false. 
    public boolean existDirectory(String path) throws IOException { 
        boolean flag = false; 
        FTPFile[] ftpFileArr = ftpClient.listFiles(path); 
        for (FTPFile ftpFile : ftpFileArr) { 
            if (ftpFile.isDirectory() 
                    && ftpFile.getName().equalsIgnoreCase(path)) { 
                flag = true; 
                break; 
            } 
        } 
        return flag; 
    } 
 
    //======================================================================= 
    //==         About file        ===== 
    // Download and Upload file using 
    // ftpUtil.setFileType(FtpUtil.BINARY_FILE_TYPE) better! 
    //======================================================================= 
 
    // #1. list & delete operation 
    // Not contains directory 
    public List<String> getFileList(String path) throws IOException { 
        // listFiles return contains directory and file, it's FTPFile instance 
        // listNames() contains directory, so using following to filer directory. 
        //String[] fileNameArr = ftpClient.listNames(path); 
        FTPFile[] ftpFiles= ftpClient.listFiles(path); 
         
        List<String> retList = new ArrayList<String>(); 
        if (ftpFiles == null || ftpFiles.length == 0) { 
            return retList; 
        } 
        for (FTPFile ftpFile : ftpFiles) { 
            if (ftpFile.isFile()) { 
                retList.add(ftpFile.getName()); 
            } 
        } 
        return retList; 
    } 
 
    public boolean deleteFile(String pathName) throws IOException { 
        return ftpClient.deleteFile(pathName); 
    } 
 
    // #2. upload to ftp server 
    // InputStream <------> byte[]  simple and See API 
 
    public boolean uploadFile(String fileName, String newName) 
            throws IOException { 
        boolean flag = false; 
        InputStream iStream = null; 
        try { 
            iStream = new FileInputStream(fileName); 
            flag = ftpClient.storeFile(newName, iStream); 
        } catch (IOException e) { 
            flag = false; 
            return flag; 
        } finally { 
            if (iStream != null) { 
                iStream.close(); 
            } 
        } 
        return flag; 
    } 
 
    public boolean uploadFile(String fileName) throws IOException { 
        return uploadFile(fileName, fileName); 
    } 
 
    public boolean uploadFile(InputStream iStream, String newName) 
            throws IOException { 
        boolean flag = false; 
        try { 
            // can execute [OutputStream storeFileStream(String remote)] 
            // Above method return's value is the local file stream. 
            flag = ftpClient.storeFile(newName, iStream); 
        } catch (IOException e) { 
            flag = false; 
            return flag; 
        } finally { 
            if (iStream != null) { 
                iStream.close(); 
            } 
        } 
        return flag; 
    } 
 
    // #3. Down load  
 
    public boolean download(String remoteFileName, String localFileName) 
            throws IOException { 
        boolean flag = false; 
        File outfile = new File(localFileName); 
        OutputStream oStream = null; 
        try { 
            oStream = new FileOutputStream(outfile); 
            flag = ftpClient.retrieveFile(remoteFileName, oStream); 
        } catch (IOException e) { 
            flag = false; 
            return flag; 
        } finally { 
            oStream.close(); 
        } 
        return flag; 
    } 
     
    public InputStream downFile(String sourceFileName) throws IOException { 
        return ftpClient.retrieveFileStream(sourceFileName); 
    } 

 

分享到:
评论

相关推荐

    Apache Common-net Ftp客户端实例

    在本文中,我们将深入探讨如何使用Apache Commons Net库中的FTP客户端类来实现FTP文件传输操作。首先,我们需要理解FTP的基本概念。 FTP是一种应用层协议,用于在互联网上进行文件传输。它允许用户从远程服务器上传...

    Spring Boot整合FTPClient线程池的实现示例

    FTPClient 是一个基于 Java 的 FTP 客户端库,提供了丰富的 FTP 操作 API,例如上传、下载、删除文件等。然而,在高并发场景下,频繁创建和销毁 FTPClient 对象可能会对服务器造成很大的压力。 为了解决这个问题,...

    org.apache.commons.net.ftp的官方完整jar包

    org.apache.commons.net.ftp的官方完整jar包 放心使用

    FTP依赖jar包,最新版

    其中,FTPClient组件提供了全面的FTP协议支持,包括上传、下载文件,创建和删除目录,设置权限等操作。该库还支持FTP over SSL/TLS(FTPS)和FTPES(Explicit FTP over SSL/TLS),确保数据传输的安全性。 2. **...

    FTP操作示例

    `FTPDemo.java`很可能是包含实际操作的示例程序,它可能展示了如何使用`FTPClientTemplate`进行文件上传、下载、删除等操作。`FtpRuntimeException.java`可能是自定义的异常类,用于捕获FTP操作过程中可能出现的问题...

    FTPClient.listFiles()获取文件为空的问题.

    ftpClient.changeWorkingDirectory(path); ftpClient.enterLocalPassiveMode(); //由于apache不支持中文语言环境,通过定制类解析中文日期类型 ... FTPFile[] files = ftpClient.listFiles();

    java多线程ftp 上传下载

    7. **线程安全**:在多线程环境中,由于FTPClient对象不是线程安全的,所以每个线程应拥有独立的`FTPClient`实例,或者使用同步机制(如synchronized关键字)来保证对FTPClient的操作是互斥的。 8. **资源释放**:...

    SpringBoot2.2+commons-pool2实现多Ftp连接池完整项目,开箱即用,经过长期生产使用稳定可靠

    使用JDK1.8、SpringBoot2.2.10.RELEASE、lombok1.18.8、guava23.0、hutool5.3.10、commons-pool2 2.7.0、tika1.22等实现多Ftp连接池实现,通过守护线程实现连接池内连接可用性校验,配置最大、最小连接个数防止Ftp...

    FTP Jar包 Commons等 绝对能用

    总结一下,"FTP Jar包 Commons等 绝对能用"指的是使用Apache Commons Net库进行FTP操作,这个库提供了全面的FTP功能,包括上传和下载,且经过验证,可以稳定地工作在Java环境中。通过理解并熟练使用这个库,开发者...

    用于FTP文件传输的命令追踪

    你可以通过创建`FTPClient`实例并调用其方法来执行FTP操作,如登录服务器、改变工作目录、上传或下载文件等。 2. **连接设置**:在使用`FTPClient`之前,你需要设置服务器的主机名、端口号、用户名和密码。这些可以...

    common-io,common-net打包奉送

    Apache Commons IO库(common-io)是一个专注于I/O操作的实用工具集,提供了大量的静态方法来处理文件、流、过滤器、读写操作等。其中包含的功能有: 1. 文件操作:如创建、复制、移动、删除文件,以及检查文件属性...

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

    总结来说,通过Apache Commons Net库,我们可以轻松地在Android应用中实现FTP功能,进行文件的上传、下载、目录操作等,从而实现与远程服务器的数据交换。不过,注意在实际开发中,应根据具体需求选择合适的FTP操作...

    Java FTPClient连接池的实现

    创建和销毁FTPClient对象是非常耗费资源的操作,因此,我们可以使用连接池来复用这些对象,减少创建和销毁的次数,从而提高性能。 那么,什么是对象池呢?对象池是一种机制,它可以管理对象池中对象的生命周期,...

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

    在描述中提到的博客链接可能包含了一个完整的示例代码,演示了如何使用Apache Commons Net库进行FTP操作。通常,这些示例会涵盖文件的打开、关闭、错误处理以及FTP连接的管理和断开等关键步骤。 标签中提到的“源码...

    SWT(JFace) FTP客户端实现

    1. `FTPClient` - Apache Commons Net库中的类,负责建立FTP连接和执行FTP命令。 2. `ProtocolCommandListener` - 监听FTP命令的接口,可以用来跟踪FTP会话中的事件。 3. `FTPFile` - 表示FTP服务器上的文件或目录的...

    ftp定时下载

    【common包】通常指的是Apache Commons,这是一个包含各种实用工具类的Java库,提供了丰富的功能,如文件处理、IO操作、日期时间处理等。在FTP下载的上下文中,可能使用了Apache Commons Net库,它提供了一系列与FTP...

    commons-net-3.8.0-bin.tar.gz

    1. FTPClient:这个类是与FTP服务器交互的主要接口,提供了执行FTP命令、处理会话状态和管理文件操作的方法。 2. FTPSClient:扩展了FTPClient,增加了对安全FTP的支持,通过TLS/SSL提供数据加密。 3. FTPFile:表示...

    commons-net-jar包.zip

    库提供了FTPClient、FTPSSLClient、FTPSSLSocketFactory等类,可以实现FTP的连接、登录、文件上传、下载、删除、重命名等操作,并且支持主动和被动模式,以及SSL/TLS加密。 3. **Telnet功能** Telnet协议在commons...

    java代码规范示例

    在 FTP 连接的实现中,使用了 Apache commons-net 库,提供了 FTP 客户端的实现。这个库提供了对 FTP 服务器的连接、上传和下载文件等功能。在这个示例中,使用了 FTPClient 类来实现 FTP 连接,配置了 FTP 服务器的...

Global site tag (gtag.js) - Google Analytics