首页

基于ftp4j包实现连接文件服务器代码工具类代码模拟客户端FTPClient常用操作行为

标签:sauronsoftware,ftp4j,FTPClient,工具类,ftp4j-1.6.jar,apache     发布时间:2016-11-30   

通过sauronsoftware提供的ftp4j-1.6.jar包(下载)模拟ftp客户端常用的行为操作(登录/出、上传、移除&移除等)来连接文件服务器ftp(如apache ftp),该工具类FTPUtil代码实现了登录ftp服务器进行创建目录、删除目录、删除文件、登录、登出及切换目录等,具体内容如下

import it.sauronsoftware.ftp4j.FTPClient;@b@import it.sauronsoftware.ftp4j.FTPException;@b@import it.sauronsoftware.ftp4j.FTPFile;@b@import it.sauronsoftware.ftp4j.FTPIllegalReplyException;@b@@b@import java.io.File;@b@import java.io.IOException;@b@import java.net.URL;@b@import java.util.Properties;@b@@b@public class FTPUtil {@b@@b@    private Properties ftpInfo = new Properties();@b@@b@    private FTPClient ftpClient = null;@b@@b@    {@b@        try {@b@            ftpInfo.load(SftpUtil.class.getResourceAsStream("/ftpInfo.properties"));@b@        } catch (IOException e) {@b@            // TODO 自动生成的 catch 块@b@            e.printStackTrace();@b@        }@b@@b@    }@b@@b@    private FTPUtil() {@b@    }@b@@b@    public static FTPUtil getInstance() {@b@        return new FTPUtil();@b@    }@b@@b@    /**@b@     * 创建目录@b@     * @param client@b@     *            FTP客户端对象@b@     * @param dir@b@     *            目录@b@     * @throws Exception@b@     */@b@    public void mkdirs(FTPClient client, String dir) throws Exception {@b@        if (dir == null) {@b@            return;@b@        }@b@        dir = dir.replace("\\", "/");@b@        String[] dirs = dir.split("/");@b@        for (int i = 0; i < dirs.length; i++) {@b@            dir = dirs[i];@b@            if (dir != null && !"".equals(dir)) {@b@                if (!existsDirectory(client, dir)) {@b@                    client.createDirectory(dir);@b@                }@b@                client.changeDirectory(dir);@b@            }@b@        }@b@    }@b@@b@@b@@b@    /**@b@     * 判断目录是否存在@b@     * @param client@b@     *            FTP 客户端对象@b@     * @param dir目录@b@     * @return@b@     * @throws Exception@b@     */@b@    public boolean existsDirectory(FTPClient client, String dir) throws Exception {@b@        try {@b@            String tempPath = client.currentDirectory();@b@            client.changeDirectory(dir);@b@            client.changeDirectory(tempPath);@b@            return true;@b@        } catch (Exception e) {@b@            return false;@b@        }@b@    }@b@@b@    /**@b@     * 判断当前为文件还是目录@b@     * @param client@b@     *            FTP客户端对象@b@     * @param dir@b@     *            文件或目录@b@     * @return -1、文件或目录不存在 0、文件 1、目录@b@     * @throws Exception@b@     */@b@    public int getFileType(FTPClient client, String dir) throws Exception {@b@        FTPFile[] files = null;@b@        try {@b@            files = client.list(dir);@b@        } catch (Exception e) {@b@            e.printStackTrace();@b@            System.out.println(e.getClass().getName());@b@            return -1;@b@        }@b@        if (files.length > 1) {@b@            return FTPFile.TYPE_DIRECTORY;@b@        } else if (files.length == 1) {@b@            FTPFile f = files[0];@b@            if (f.getType() == FTPFile.TYPE_DIRECTORY) {@b@                return FTPFile.TYPE_DIRECTORY;@b@            }@b@            String path = dir + "/" + f.getName();@b@            try {@b@                int len = client.list(path).length;@b@                if (len == 1) {@b@                    return FTPFile.TYPE_DIRECTORY;@b@                } else {@b@                    return FTPFile.TYPE_FILE;@b@                }@b@            } catch (Exception e) {@b@                return FTPFile.TYPE_FILE;@b@            }@b@        } else {@b@            try {@b@                client.changeDirectory(dir);@b@                client.changeDirectoryUp();@b@                return FTPFile.TYPE_DIRECTORY;@b@            } catch (Exception e) {@b@                return -1;@b@            }@b@        }@b@    }@b@@b@    /**@b@     * 获取FTP目录@b@     * @param url@b@     *            原FTP目录@b@     * @param dir@b@     *            目录@b@     * @return@b@     * @throws Exception@b@     */@b@    public URL getURL(URL url, String dir) throws Exception {@b@        String path = url.getPath();@b@        if (!path.endsWith("/") && !path.endsWith("\\")) {@b@            path += "/";@b@        }@b@        dir = dir.replace("\\", "/");@b@        if (dir.startsWith("/")) {@b@            dir = dir.substring(1);@b@        }@b@        path += dir;@b@        return new URL(url, path);@b@    }@b@@b@    /**@b@     * 获取FTP目录@b@     * @param dir@b@     *            目录@b@     * @return@b@     * @throws Exception@b@     */@b@    public URL getURL(String dir) throws Exception {@b@        return getURL(new URL("ftp://" + ftpInfo.getProperty("host") + ":" + ftpInfo.getProperty("port")), dir);@b@    }@b@@b@    /**@b@     * 连接并登录FTP服务器@b@     * @return@b@     * @throws Exception@b@     */@b@    public boolean login() throws Exception {@b@        try {@b@            if (ftpClient == null) {@b@                ftpClient = new FTPClient();@b@            }@b@            // 建立连接@b@            if (!ftpClient.isConnected()) {@b@                ftpClient.connect(ftpInfo.getProperty("host"), Integer.parseInt(ftpInfo.getProperty("port")));@b@@b@                ftpClient.setType(FTPClient.TYPE_BINARY);@b@                ftpClient.setCharset("utf-8");@b@                System.out.println("建立连接");@b@            }@b@        } catch (Exception e) {@b@            e.printStackTrace();@b@            System.out.println("与FTP服务器建立连接失败!" + e.getMessage());@b@        }@b@        try {@b@            if (!ftpClient.isAuthenticated()) {@b@                ftpClient.login(ftpInfo.getProperty("username"), ftpInfo.getProperty("password"));@b@                System.out.println("认证通过");@b@            }@b@        } catch (Exception e) {@b@            e.printStackTrace();@b@            System.out.println("登录FTP服务器失败!" + e.getMessage());@b@        }@b@        return true;@b@    }@b@@b@    /**@b@     * 退出并关闭FTP连接@b@     */@b@    public void close() {@b@        if (null != ftpClient) {@b@            try {@b@                ftpClient.disconnect(true);// 安全退出@b@            } catch (Exception e) {@b@                e.printStackTrace();@b@                System.out.println("安全退出FTP服务时异常!" + e.getMessage());@b@            }@b@        }@b@@b@    }@b@@b@    /**@b@     * 注销客户端连接@b@     * @throws Exception@b@     */@b@    public void logout() throws Exception {@b@        logout(ftpClient);@b@    }@b@@b@    /**@b@     * 注销客户端连接@b@     * @param client@b@     *            FTP客户端对象@b@     * @throws Exception@b@     */@b@    public void logout(FTPClient client) throws Exception {@b@        if (client != null) {@b@            try {@b@                client.logout(); // 退出登录@b@            } catch (FTPException fe) {@b@                throw new Exception(fe.getMessage());@b@            } catch (Exception e) {@b@                throw e;@b@            } finally {@b@                if (client.isConnected()) { // 断开连接@b@                    client.disconnect(true);@b@                }@b@            }@b@        }@b@    }@b@@b@    /**@b@     * 下载文件@b@     * @param localFilePath本地文件名及路径@b@     * @param remoteFileName@b@     *            远程文件名称@b@     * @return@b@     * @throws Exception@b@     */@b@    public void downloadFile(String localFilePath, String remoteFileName) throws Exception {@b@        File localFile = new File(localFilePath);@b@        try {@b@            ftpClient.download(remoteFileName, localFile);@b@        } catch (Exception e) {@b@            e.printStackTrace();@b@            System.out.println("下载" + remoteFileName + "时出现异常!" + e.getMessage());@b@            throw e;@b@        }@b@    }@b@@b@    /**@b@     * 上传文件或目录@b@     * @b@     * @param dir@b@     *            ftp服务器目标路径@b@     * @param files@b@     *            文件或目录对象数组@b@     * @throws Exception@b@     */@b@    public void upload(String dir, File... files) throws Exception {@b@        upload(dir, false, files);@b@    }@b@@b@    /**@b@     * 上传文件或目录到ftp服务器@b@     * @b@     * @param dir@b@     *            ftp服务器目标路径@b@     * @param del@b@     *            是否删除源文件,默认为false@b@     * @param file@b@     *            文件或目录对象数组@b@     * @throws Exception@b@     */@b@    public void upload(String dir, boolean del, File... files) throws Exception {@b@        if (files == null) {@b@            return;@b@        }@b@        try {@b@            if (dir != null && !"".equals(dir)) {@b@                mkdirs(ftpClient, dir); // 创建文件@b@            }@b@            for (File file : files) {@b@                if (file.isDirectory()) { // 上传目录@b@                    uploadFolder(getURL(dir), file, del);@b@                } else {@b@                    ftpClient.upload(file); // 上传文件@b@                    if (del) { // 删除源文件@b@                        file.delete();@b@                    }@b@                }@b@            }@b@        } finally {@b@            // logout(ftpClient);@b@        }@b@    }@b@@b@    public void changeDirectory(String dir) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException {@b@        ftpClient.changeDirectory(dir);@b@    }@b@@b@    /**@b@     * 删除ftp服务文件或目录@b@     * @b@     * @param dir@b@     *            文件或目录数组@b@     * @throws Exception@b@     */@b@    public void deleteFile(String... dirs) throws Exception {@b@        if (dirs == null || dirs.length <= 0) {@b@            return;@b@        }@b@        try {@b@            for (String dir : dirs) {@b@                ftpClient.changeDirectory("/"); // 切换至根目录@b@                ftpClient.deleteFile(dir);@b@            }@b@        } finally {@b@            // logout(client);@b@        }@b@    }@b@@b@    /**@b@     * 删除ftp服务器上的目录@b@     * @b@     * @param dir@b@     *            文件或目录数组@b@     * @throws Exception@b@     */@b@    public void delete(String... dirs) throws Exception {@b@        if (dirs == null || dirs.length <= 0) {@b@            return;@b@        }@b@        try {@b@            int type = -1;@b@            for (String dir : dirs) {@b@                ftpClient.changeDirectory("/"); // 切换至根目录@b@                type = getFileType(ftpClient, dir); // 获取当前类型@b@                if (type == 0) { // 删除文件@b@                    ftpClient.deleteFile(dir);@b@                } else if (type == 1) { // 删除目录@b@                    deleteFolder(getURL(dir));@b@                }@b@                System.out.println(dir + " delete success!!!");@b@            }@b@        } finally {@b@            // logout(client);@b@        }@b@    }@b@@b@    /**@b@     * 通过url删除ftp服务器目录@b@     * @b@     * @param client@b@     *            FTP客户端对象@b@     * @param url@b@     *            FTP URL@b@     * @throws Exception@b@     */@b@    private void deleteFolder(URL url) throws Exception {@b@        String path = url.getPath();@b@        ftpClient.changeDirectory(path);@b@        FTPFile[] files = ftpClient.list();@b@        String name = null;@b@        for (FTPFile file : files) {@b@            name = file.getName();@b@            // 排除隐藏目录@b@            if (".".equals(name) || "..".equals(name)) {@b@                continue;@b@            }@b@            if (file.getType() == FTPFile.TYPE_DIRECTORY) { // 递归删除子目录@b@                deleteFolder(getURL(url, file.getName()));@b@            } else if (file.getType() == FTPFile.TYPE_FILE) { // 删除文件@b@                ftpClient.deleteFile(file.getName());@b@            }@b@        }@b@        ftpClient.changeDirectoryUp();@b@        ftpClient.deleteDirectory(url.getPath()); // 删除当前目录@b@    }@b@@b@    /**@b@     * 上传目录@b@     * @param client@b@     *            FTP客户端对象@b@     * @param parentUrl@b@     *            父节点URL@b@     * @param file@b@     *            目录@b@     * @throws Exception@b@     */@b@    private void uploadFolder(URL parentUrl, File file, boolean del) throws Exception {@b@        ftpClient.changeDirectory(parentUrl.getPath());@b@        String dir = file.getName(); // 当前目录名称@b@        URL url = getURL(parentUrl, dir);@b@        if (!existsDirectory(ftpClient, url.getPath())) { // 判断当前目录是否存在@b@            ftpClient.createDirectory(dir); // 创建目录@b@        }@b@        ftpClient.changeDirectory(dir);@b@        File[] files = file.listFiles(); // 获取当前文件夹所有文件及目录@b@        for (int i = 0; i < files.length; i++) {@b@            file = files[i];@b@            if (file.isDirectory()) { // 如果是目录,则递归上传@b@                uploadFolder(url, file, del);@b@            } else { // 如果是文件,直接上传@b@                ftpClient.changeDirectory(url.getPath());@b@                ftpClient.upload(file);@b@                if (del) { // 删除源文件@b@                    file.delete();@b@                }@b@            }@b@        }@b@    }@b@@b@    /**@b@     * 测试ftp连接@b@     * @b@     * @return 0连通,1:连接失败;2:连接但登陆失败。@b@     * @throws Exception@b@     */@b@    public int test() throws Exception {@b@        int flag = 0;@b@        try {@b@            ftpClient = new FTPClient();@b@            // 建立连接@b@            ftpClient.connect(ftpInfo.getProperty("host"), Integer.parseInt(ftpInfo.getProperty("port")));@b@            ftpClient.setType(FTPClient.TYPE_AUTO);@b@        } catch (Exception e) {@b@            flag = 1;@b@        }@b@@b@        if (ftpClient.isConnected()) {@b@            try {@b@                ftpClient.login(ftpInfo.getProperty("username"), ftpInfo.getProperty("password"));@b@                if (!ftpClient.isAuthenticated()) {@b@                    flag = 2;@b@                } else {@b@                    flag = 0;@b@                    ftpClient.disconnect(true);@b@                }@b@            } catch (Exception e) {@b@                e.printStackTrace();@b@                flag = 2;@b@            }@b@        } else {@b@            flag = 1;@b@        }@b@@b@        return flag;@b@    }@b@@b@    public static void main(String[] args) throws Exception {@b@        FTPUtil ftp = FTPUtil.getInstance();@b@        ftp.login();@b@        ftp.delete("ENV.txt");@b@        ftp.logout();@b@@b@    }@b@@b@}

相关配置ftpInfo.properties内容如下所示

host=127.0.0.1@b@username=admin@b@password=123456@b@port=2121