Java 实现ftp 文件上传、下载和删除

实现FTP相关功能

1、下载相应的jar包

  commons-net-3.6.jar

2、代码实现

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 org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 * FTP 操作类
 * @author d
 * @version 1.0
 * 2019.12.12
 */
public class FtpUtil {
    
    public static void main(String[] args) {
        FtpUtil ftpUtil = new FtpUtil();
        ftpUtil.downLoadFile("/", "", "D:/test");
//        ftpUtil.uploadFile("/1", "1.zip", "D:/test/1.zip");
//        ftpUtil.deleteFile("/1", "1.zip");
    }
    
    /**
     * Ftp 服务器地址
     **/
    public String hostname = "127.0.0.1";
    /**
     * Ftp 端口号
     **/
    public int port = 21;
    /**
     * Ftp 登录账号
     **/
    public String username = "root";
    /**
     * Ftp 登录密码
     **/
    public String password = "root";
    /**
     * 设置缓冲区大小4M
     **/
    private static final int BUFFER_SIZE = 1024 * 1024 * 4;
    /**
     * Ftp 操作对象
     **/
    public FTPClient ftpClient = null;

    /**
     * 连接FTP服务器
     *
     * @param address  地址
     * @param port     端口
     * @param username 用户名
     * @param password 密码
     */
    private void login() {
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        try {
            ftpClient.connect(hostname, port);
            ftpClient.login(username, password);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//文件类型为二进制文件
            ftpClient.setBufferSize(BUFFER_SIZE);//限制缓冲区大小
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                closeConnect();
                System.out.println("FTP服务器连接失败");
            }
        } catch (Exception e) {
            System.out.println("FTP登录失败" + e.getMessage());
        }
    }

    /**
     * 关闭FTP连接
     */
    private void closeConnect() {
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                System.out.println("关闭FTP连接失败" + e.getMessage());
            }
        }
    }
    
    /**
     * 下载文件
     * @param ftpPath FTP文件目录
     * @param fileName 需下载的文件名
     * @param savePath 下载后的文件路径
     * @return 返回是否下载成功 true
     */
    public Boolean downLoadFile(String ftpPath, String fileName, String savePath){
        login();
        OutputStream os = null;
        if (ftpClient != null) {
            try {
                //判断是否存在该目录
                if (!ftpClient.changeWorkingDirectory(ftpPath)) {
                    System.out.println("/" + ftpPath + "该目录不存在");
                    return false;
                }
                ftpClient.enterLocalPassiveMode();//设置被动模式,开通一个端口来传输数据

                FTPFile[] ftpFiles = ftpClient.listFiles();
                // 判断该目录下是否有文件
                if (ftpFiles == null || ftpFiles.length == 0) {
                    System.out.println("/" + ftpPath + "该目录下无文件");
                    return false;
                }
                for(FTPFile file : ftpFiles){
                    if(fileName.equals("") || fileName.equalsIgnoreCase(file.getName())){//文件名称为"",下载指定文件
                        if(!file.isDirectory()){//是否文件夹 
                            File saveFile = new File(savePath + "/" + file.getName()); 
                            os = new FileOutputStream(saveFile); 
                            ftpClient.retrieveFile(file.getName(), os); 
                            os.close(); 
                        }
                    }
                }
                return true;
            } catch (IOException e) {
                System.out.println("下载文件失败" + e.getMessage());
            } finally {
                if(null != os){
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } 
                }
                closeConnect();
            }
        }
        return false;
    }

    /**
    * 上传文件
    * @param savePath FTP保存目录
    * @param fileName 上传到FTP的文件名
    * @param filePath 待上传文件的名称(绝对地址)
    * @return
    */
    public boolean uploadFile(String savePath, String fileName,String filePath){
        login();
        boolean flag = false;
        InputStream inputStream = null;
        if (ftpClient != null) {
            try{
                inputStream = new FileInputStream(new File(filePath));
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.makeDirectory(savePath);
                ftpClient.changeWorkingDirectory(savePath);
                ftpClient.storeFile(fileName, inputStream);
                inputStream.close();
                flag = true;
            }catch (Exception e) {
                e.printStackTrace();
            }finally{
                if(null != inputStream){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } 
                }
                closeConnect();
            }
        }
        return flag;
    }

    /** * 删除文件 * 
    * @param pathname FTP服务器保存目录
    * @param filename 要删除的文件名称 
    * @return */ 
    public boolean deleteFile(String filePath, String filename){
        login();
        boolean flag = false; 
        if (ftpClient != null) {
            try { 
                ftpClient.changeWorkingDirectory(filePath);
                ftpClient.dele(filename); 
                flag = true; 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } finally {
                closeConnect();
            }
        }
        return flag; 
    }
    
}

 

posted @ 2019-12-16 15:46  LEON D  阅读(3076)  评论(3编辑  收藏  举报