apache的ftpclient的使用

本文介绍了一个Java实现的FTP客户端工具类,包括连接FTP服务器、文件上传与下载、目录管理等功能。提供了详细的代码示例及说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;  
      
    /** 
     * @param path     上传到ftp服务器哪个路径下 
     * @param addr     地址 
     * @param port     端口号 
     * @param username 用户名 
     * @param password 密码 
     * @return 
     * @throws Exception 
     */  
	//("", "localhost", 2121, "admin", "admin")
    private boolean connect(String path, String addr, int port, String username, String password) throws Exception {  
        boolean result = false;  
        ftpClient = new FTPClient();  
        int reply;  
        ftpClient.connect(addr, port);  
        ftpClient.login(username, password);  
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
        reply = ftpClient.getReplyCode();  
        if (!FTPReply.isPositiveCompletion(reply)) {  
            ftpClient.disconnect();  
            return result;  
        }  
        ftpClient.changeWorkingDirectory(path);  
        result = true;  
        return result;  
    } 
	/**
	*@param fileType上传文件的类型
	*FTP.BINARY_FILE_TYPE | FTP.ASCII_FILE_TYPE
	* @throws Exception 
	*/
    public void setFileType(int fileType) throws IOException {  
        ftpClient.setFileType(fileType);  
    }  
  
    public void closeServer() throws IOException {  
        if (ftpClient.isConnected()) {  
            ftpClient.disconnect();  
        }  
    }  
    //=======================================================================  
    //==        关于文件夹的操作      =====  
    // 下面的方法最好用相对路径为好  
    //=======================================================================  
      
    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);  
    }  
      
    // 删除文件夹以及文件夹里的文件  
    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);  
    }  
      
    // 检查路径是否存在,存在返回true,否则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;  
    }  
  
    //=======================================================================  
    //==         文件操作        =====  
    // 上传和下载文件  
    // ftpUtil.setFileType(FtpUtil.BINARY_FILE_TYPE) better!  
    //=======================================================================  
  
    // #1. 列表和删除按操作
    // 不包含文件夹
    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. 上传到服务器  
    // 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. 下载   
  
    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);  
    }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值