首页>代码>Java swing实现Ftp客户端工具(MVC模式)>/FtpClient/src/com/exercise/controller/utils/FtpUtil.java
package com.exercise.controller.utils;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Vector;

import com.enterprisedt.net.ftp.FTPConnectMode;
import com.enterprisedt.net.ftp.FTPException;
import com.enterprisedt.net.ftp.FTPFile;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.FileTransferClient;
import com.enterprisedt.util.debug.Level;
import com.enterprisedt.util.debug.Logger;
import com.exercise.model.bean.FileBean;
import com.exercise.model.bean.FtpInfoBean;

/*
 *  说明:Ftp 工具类
 */
public class FtpUtil {

    private static final Logger log = Logger.getLogger(FtpUtil.class);
    private static FileTransferClient ftp = null;
    private static String currentPath;

    //连接服务器,如果连接成功返回true
    public static boolean connectToServer(FtpInfoBean ftpInfoBean) {
        Logger.setLevel(Level.INFO);
        try {
            // create client
            log.info("Creating FTP client");
            ftp = new FileTransferClient();
            // set remote host
            log.info("Setting remote host");
            ftp.setRemoteHost(ftpInfoBean.getIp());//Ip
            ftp.setUserName(ftpInfoBean.getUsername());//用户名
            ftp.setPassword(ftpInfoBean.getPassword());//密码      
            ftp.setContentType(FTPTransferType.ASCII);//ASCII编码
            ftp.getAdvancedFTPSettings().setConnectMode(FTPConnectMode.PASV);//被动模式            
            ftp.getAdvancedSettings().setControlEncoding("gb2312");//设置编码
            // connect to the server
            log.info("Connecting to server " + ftpInfoBean.getIp());
            ftp.connect();
            log.info("Connected and logged in to server " + ftpInfoBean.getIp());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //立即断开服务器连接
    public static void disconnectFromServer() {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect(true);
            } catch (FTPException ex) {
                java.util.logging.Logger.getLogger(FtpUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(FtpUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
        }
    }

    //获得 ftp 服务器文件列表
    public static FTPFile[] getFileList(FtpInfoBean ftpInfoBean, String remotePath) {
        Logger.setLevel(Level.INFO);
        FTPFile[] files = null;
        try {
            boolean isConnected = true;
            //如果连接为空或者断开,则重新连接
            if (ftp == null || !ftp.isConnected()) {
                isConnected = connectToServer(ftpInfoBean);
            }
            //连接正常后获取文件列表
            if (isConnected) {
                log.info("Getting current directory listing");
                if (StringUtil.isEmpty(remotePath)) {
                    files = ftp.directoryList(".");
                    currentPath = "/";
                } else {
                    currentPath = remotePath;
                    files = ftp.directoryList(remotePath);

                }
                // Shut down client
                log.info("Quitting client");
                ftp.disconnect();
                log.info("Example1SimpleMenu complete");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return files;
    }

    //去除不可操作类型,根据FTPFile[] 返回 List<FileBean>
    public static Vector<FileBean> trim(FTPFile[] files) {
        Vector<FileBean> listData = new Vector<FileBean>();
        Vector<FileBean> folderData = new Vector<FileBean>();
        Vector<FileBean> fileData = new Vector<FileBean>();
        for (int i = 0; i < files.length; i++) {
            FileBean fileBean = new FileBean();
            FTPFile ftpFile = files[i];
            if (isOperable(ftpFile)) {
                fileBean.setName(ftpFile.getName());
                fileBean.setPath(currentPath);
                fileBean.setSize(ftpFile.size());
                if (ftpFile.isDir()) {
                    fileBean.setType(FileBean.FileType.folder);
                    folderData.add(fileBean);
                } else {
                    fileBean.setType(FileBean.FileType.file);
                    fileData.add(fileBean);
                }
                fileBean.setLastModified(ftpFile.lastModified());

            }
        }
        listData.addAll(folderData);//按先文件夹,后文件的顺序排序
        listData.addAll(fileData);
        return listData;
    }

    //根据用户信息和文件路径,直接获得经过转换后的FileBean集合
    public static Vector<FileBean> getTrimedFileList(FtpInfoBean ftpInfoBean, String remotePath) {
        return trim(getFileList(ftpInfoBean, remotePath));
    }

    //判断文件是否能被用户进行简单操作
    private static boolean isOperable(FTPFile ftpFile) {
        String filename = ftpFile.getName();
        if (filename.equals(".") || filename.equals("..")) {
            return false;
        }
        return true;
    }

    //判断用户登录信息是否有效
    public static boolean isValid(FtpInfoBean ftpInfoBean) {
        return connectToServer(ftpInfoBean);
    }

    //上传文件到服务器
    public static void uploadFile(FtpInfoBean ftpInfoBean, FileBean fileBean,
            String localFileName, String remoteFileName) {
        Logger.setLevel(Level.INFO);
        boolean isConnected = true;
        //如果连接为空或者断开,则重新连接
        try {
            if (ftp == null || !ftp.isConnected()) {
                isConnected = connectToServer(ftpInfoBean);
            }
            //连接正常后上传文件
            if (isConnected) {
                log.info("Uploading file");
                ftp.changeDirectory(currentPath);//定位到当前文件夹位置 
                ftp.uploadFile(localFileName, remoteFileName);
                log.info("File uploaded");
            }
        } catch (FTPException ex) {
            java.util.logging.Logger.getLogger(FtpUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(FtpUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
    }

    //删除文件或文件夹
    public static void deleteFile(FtpInfoBean ftpInfoBean, FileBean fileBean) {
        Logger.setLevel(Level.INFO);
        boolean isConnected = true;
        try {
            if (ftp == null || !ftp.isConnected()) {
                isConnected = connectToServer(ftpInfoBean);
            }
            if (isConnected) {
                if (fileBean.getType().equals(FileBean.FileType.file)) {
                    ftp.changeDirectory(currentPath);
                    ftp.deleteFile(fileBean.getName());
                } else if (fileBean.getType().equals(FileBean.FileType.folder)) {
                    String relatePath = currentPath + "/" + fileBean.getName();
                    FTPFile[] data = ftp.directoryList(relatePath);
                    if (trim(data).isEmpty()) {
                        ftp.changeDirectory(currentPath);
                        ftp.deleteDirectory(fileBean.getName());
                    };
                }
            }
        } catch (FTPException ex) {
            java.util.logging.Logger.getLogger(FtpUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(FtpUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            java.util.logging.Logger.getLogger(FtpUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) {
        String host = "127.0.0.1";
        String username = "test";
        String password = "test";
        FtpInfoBean ftpInfoBean = new FtpInfoBean(host, username, password);
        connectToServer(ftpInfoBean);
        Vector<FileBean> list = getTrimedFileList(ftpInfoBean, null);
        for (int i = 0; i < list.size(); i++) {
            FileBean fb = list.get(i);
            System.out.println(fb.toString());
        }
    }

    public static void downloadFile(FtpInfoBean ftpInfoBean, String localPath, FileBean fileBean) {
        Logger.setLevel(Level.INFO);
        boolean isConnected = true;
        String ftpPath=fileBean.getPath()+"/"+fileBean.getName();
        String Path=localPath+fileBean.getPath();
        System.out.println("===="+Path+"路径地址");
        File file=new File(Path);
        if(!file.exists()){//如果文件夹不存在
			file.mkdir();//创建文件夹
		}
        try {
            if (ftp == null || !ftp.isConnected()) {
                isConnected = connectToServer(ftpInfoBean);
            }
            if (isConnected) {
            	System.out.println("============"+localPath+"==========");
            	System.out.println("========="+fileBean.getPath()+"========="+ftpPath);
            	System.out.println("========"+fileBean.getName()+"=========");
            	System.out.println("========"+fileBean.getType()+"=========");
                ftp.downloadFile(localPath, ftpPath);
            }
        } catch (FTPException ex) {
            java.util.logging.Logger.getLogger(FtpUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(FtpUtil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

    }
}
最近下载更多
zengxq056  LV2 2022年10月3日
annazhang  LV29 2021年7月24日
Little already  LV3 2021年6月22日
lilinfeng  LV1 2021年5月25日
冬日  LV1 2021年5月21日
陈学文  LV1 2021年4月30日
2469095052  LV8 2020年12月14日
guaixia163  LV13 2020年11月11日
675104182  LV14 2020年9月22日
小小滑头鱼  LV26 2020年7月15日
最近浏览更多
kevin_2023  LV1 2023年10月26日
yangxb2  LV10 2023年7月11日
as365049954  LV2 2022年10月16日
zengxq056  LV2 2022年10月3日
1576765285  LV1 2022年9月13日
qwqw900619  LV4 2022年9月7日
哎呀马吖  LV6 2022年8月25日
qsyqsy 2022年6月2日
暂无贡献等级
sunfanlin  LV2 2022年5月18日
June06  LV2 2022年5月3日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友