Thursday, June 18, 2015

Download Files and Directories from FTP

Download Files and Directories from FTP by using Apache Commons-net 3.3

Below java file will be used to download files or folders from FTP, to setup this program running in eclipse you need to setup the required jar files into the class path, for that you need to have Apache-Commons-net 3.3 jar files.

Please find the link here to download the jars.

https://drive.google.com/file/d/0BxIDTv_7kcnfMFJiTlUwYzl4aWs/view?usp=sharing

This program needs a properties file as a input to the FTP_Utility.java main method.

ftpproperties.properties

serverAddress=127.0.0.1
userId=demo   
password=demo
remoteDirectory=/
localDirectory=/filesinFTP
savedDirectory = C:\\downloadedfiles

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTP_Utility {

    public static void main(String[] args) {
        GetCDRFilesFromFTP getMyFiles = new GetCDRFilesFromFTP();
        if (args.length < 1) {
            System.err.println("Usage: java " + getMyFiles.getClass().getName() + " Properties_file");
            System.exit(1);
        }
        String propertiesFile = args[0].trim();
        getMyFiles.startFTP(propertiesFile);
    }
}


class GetCDRFilesFromFTP {

static Properties props;
public boolean startFTP(String propertiesFile){

        props = new Properties();

        try {

            props.load(new FileInputStream("properties/" + propertiesFile));
            String serverAddress = props.getProperty("serverAddress").trim();
            String userId = props.getProperty("userId").trim();
            String password = props.getProperty("password").trim();
            String remoteDirectory = props.getProperty("remoteDirectory").trim();
            String localDirectory = props.getProperty("localDirectory").trim();
            String savedDirectory = props.getProperty("savedDirectory").trim();
            //new ftp client
            FTPClient ftp = new FTPClient();
            //try to connect
            ftp.connect(serverAddress);
            //login to server
            if(!ftp.login(userId, password))
            {
                ftp.logout();
                return false;
            }
            int reply = ftp.getReplyCode();
            //FTPReply stores a set of constants for FTP reply codes.
            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                return false;
            }

            //enter passive mode

            ftp.enterLocalPassiveMode();
            //get system name
            System.out.println("Remote system is " + ftp.getSystemType());
            //change current directory
            ftp.changeWorkingDirectory(remoteDirectory);
            System.out.println("Current directory is " + ftp.printWorkingDirectory());
       
            downloadDirectory(ftp, localDirectory, remoteDirectory, savedDirectory);
       
            ftp.logout();
            ftp.disconnect();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
        return true;
    }




/**
 * Download a whole directory from a FTP server.
 * @param ftpClient an instance of org.apache.commons.net.ftp.FTPClient class.
 * @param parentDir Path of the parent directory of the current directory being
 * downloaded.
 * @param currentDir Path of the current directory being downloaded.
 * @param saveDir path of directory where the whole remote directory will be
 * downloaded and saved.
 * @throws IOException if any network or IO error occurred.
 */
public static void downloadDirectory(FTPClient ftpClient, String parentDir,
        String currentDir, String saveDir) throws IOException {
    String dirToList = parentDir;
    if (!currentDir.equals("")) {
        dirToList += "/" + currentDir;
    }

    FTPFile[] subFiles = ftpClient.listFiles(dirToList);

    System.out.println(subFiles.length);
    if (subFiles != null && subFiles.length > 0) {
        for (FTPFile aFile : subFiles) {
            String currentFileName = aFile.getName();
            if (currentFileName.equals(".") || currentFileName.equals("..")) {
                // skip parent directory and the directory itself
                continue;
            }
            String filePath = parentDir + "/" + currentDir + "/"
                    + currentFileName;
            if (currentDir.equals("")) {
                filePath = parentDir + "/" + currentFileName;
            }

            String newDirPath = saveDir + parentDir + File.separator
                    + currentDir + File.separator + currentFileName;
            if (currentDir.equals("")) {
                newDirPath = saveDir + parentDir + File.separator
                          + currentFileName;
            }

            if (aFile.isDirectory()) {
                // create the directory in saveDir
                File newDir = new File(newDirPath);
                boolean created = newDir.mkdirs();
                if (created) {
                    System.out.println("CREATED the directory: " + newDirPath);
                } else {
                    System.out.println("COULD NOT create the directory: " + newDirPath);
                }

                // download the sub directory
                downloadDirectory(ftpClient, dirToList, currentFileName,
                        saveDir);
            } else {
                // download the file
                boolean success = downloadSingleFile(ftpClient, filePath,
                        newDirPath);
                if (success) {
                    System.out.println("DOWNLOADED the file: " + filePath);
                } else {
                    System.out.println("COULD NOT download the file: "
                            + filePath);
                }
            }
        }
    }
}

/**
 * Download a single file from the FTP server
 * @param ftpClient an instance of org.apache.commons.net.ftp.FTPClient class.
 * @param remoteFilePath path of the file on the server
 * @param savePath path of directory where the file will be stored
 * @return true if the file was downloaded successfully, false otherwise
 * @throws IOException if any network or IO error occurred.
 */
public static boolean downloadSingleFile(FTPClient ftpClient,
        String remoteFilePath, String savePath) throws IOException {
    File downloadFile = new File(savePath);

    File parentDir = downloadFile.getParentFile();
    if (!parentDir.exists()) {
        parentDir.mkdir();
    }
    
    OutputStream outputStream = new BufferedOutputStream(
            new FileOutputStream(downloadFile));
    try {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        return ftpClient.retrieveFile(remoteFilePath, outputStream);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

}

No comments: