user9066907
user9066907

Reputation:

Download all folders recursively from FTP server in Java

I want to download (or if you wanna say synchronize) the whole content of an FTP server with my local directory. I am already able to download the files and create the directories at the "first layer". But I don't know how to realize the subfolders and files in these. I just cant get a working loop. Can someone help me? Thanks in advance.

Here's my code so far:

FTPFile[] files = ftp.listFiles();

for (FTPFile file : files){
    String name = file.getName();
    if(file.isFile()){
        System.out.println(name);
        File downloadFile = new File(pfad + name);
        OutputStream os = new BufferedOutputStream(new FileOutputStream(downloadFile));
        ftp.retrieveFile(name, os);
    }else{
        System.out.println(name);
        new File(pfad + name).mkdir();
    }

}

I use the Apache Commons Net library.

Upvotes: 1

Views: 1947

Answers (2)

Martin Prikryl
Martin Prikryl

Reputation: 202262

Just put your code to a method and call it recursively, when you find a (sub)folder. This will do:

private static void downloadFolder(
    FTPClient ftpClient, String remotePath, String localPath) throws IOException
{
    System.out.println(
        "Downloading remote 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 remote 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();
            }
        }
    }
}

Upvotes: 1

lexicore
lexicore

Reputation: 43661

You can use FTPFile.isDirectory() to check if current file is a directory. If it is a directory FTPClient.changeWorkingDirectory(...) to it and continue recursively.

Upvotes: 0

Related Questions