FTPClient 删除 Ftp 上的文件夹,包括其中的文件

    /**
     * FTPClient 删除 Ftp 上的文件夹,包括其中的文件。 pathName = "/" 表示 ftp 根目录
     */
    public static boolean removeDirectoryALLFile(String hostname, int port, String username, String password, String pathName) {
        FTPClient ftpClient = new FTPClient();

        try {
            //连接FTP服务器
            ftpClient.connect(hostname, port);
            //登录FTP服务器
            ftpClient.login(username, password);
            //验证FTP服务器是否登录成功
            int replyCode = ftpClient.getReplyCode();

            if(!FTPReply.isPositiveCompletion(replyCode)){
                return false;

            }


            FTPFile[] files = ftpClient.listFiles(pathName);

            if (null != files && files.length > 0) {
                for (FTPFile file : files) {
                    if (file.isDirectory()) {
                        removeDirectoryALLFile( hostname, port, username, password, pathName + "/" + file.getName() );

                        // 切换到父目录,不然删不掉文件夹
                        ftpClient.changeWorkingDirectory(pathName.substring(0, pathName.lastIndexOf("/")));

                        ftpClient.removeDirectory(pathName);
                    } else {
                        if (!ftpClient.deleteFile(pathName + "/" + file.getName())) {
                            return false;
                        }
                    }
                }

            }

            // 切换到父目录,不然删不掉文件夹
            ftpClient.changeWorkingDirectory( pathName.substring(0, pathName.lastIndexOf("/")) );
            ftpClient.removeDirectory(pathName);
        }    catch (IOException e)    {
            e.printStackTrace();
        }

        return true;
    }


调用

 removeDirectoryALLFile( hostname, port, username, password, "/" );



猜你喜欢

转载自blog.csdn.net/beguile/article/details/80184912