Download entire FTP directory in Java (Apache Net Commons)

前端 未结 2 1973
名媛妹妹
名媛妹妹 2020-12-19 22:26

I am trying to recursively iterate through the entire root directory that I arrive at after login to the FTP server.

I am able to connect, all I really want to do fr

2条回答
  •  猫巷女王i
    2020-12-19 22:54

    A complete standalone code to download all files recursively from an FTP folder:

    private static void downloadFolder(
        FTPClient ftpClient, String remotePath, String localPath) throws IOException
    {
        System.out.println("Downloading folder " + remotePath + " to " + localPath);
    
        FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);
    
        for (FTPFile remoteFile : remoteFiles)
        {
            if (!remoteFile.getName().equals(".") && !remoteFile.getName().equals(".."))
            {
                String remoteFilePath = remotePath + "/" + remoteFile.getName();
                String localFilePath = localPath + "/" + remoteFile.getName();
    
                if (remoteFile.isDirectory())
                {
                    new File(localFilePath).mkdirs();
    
                    downloadFolder(ftpClient, remoteFilePath, localFilePath);
                }
                else
                {
                    System.out.println("Downloading file " + remoteFilePath + " to " +
                        localFilePath);
    
                    OutputStream outputStream =
                        new BufferedOutputStream(new FileOutputStream(localFilePath));
                    if (!ftpClient.retrieveFile(remoteFilePath, outputStream))
                    {
                        System.out.println("Failed to download file " + remoteFilePath);
                    }
                    outputStream.close();
                }
            }
        }
    }
    

提交回复
热议问题