FTP Connectivity examples

Click here to download eclipse supported ZIP file



This is input.properties properties file and these properties are used in the application.




ftp.source.fileLocation=/test/
destination.ftp.address=IP_Address
destination.ftp.user=USER
destination.ftp.pass=PASSWORD
backup.fileLocation=C:/backup/


This is FTPConnect.java file having the source code to execute business logic.



 

    
/**
 
 */
package com.cv.ftp.connect;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

/**
 @author Chandra Vardhan
 *
 */
public class FTPConnect {

  static Properties readPropertiesFile = new Properties();

  static {
    readPropertiesFile = readPropertiesFile();

  }

  private static final Logger LOGGER = Logger.getLogger(FTPConnect.class);

  private FTPClient ftpClient = null;
  private static String sourceDirectory = null;

  private static String destinationFtpAddress = null;
  private static String destinationFtpUserId = null;
  private static String destinationFtpPassword = null;
  private static String destinationDirectory = null;

  /*
   * (non-Javadoc)
   
   * @see com.cv.ftp.read.FTPService#sendFileViaFTP(java.lang.String)
   */
  public void sendFileViaFTP(String fileName) {
    setValues(readPropertiesFile);
    LOGGER.info("uploading file to FTP...");
    ftpClient = getFtpClient();
    InputStream file = null;
    try {

      file = new FileInputStream(fileName);
      String formatedFileName = new File(fileName).getName();

      boolean isFileStored = ftpClient.storeFile(formatedFileName, file);
      LOGGER.info(String.format("store file to ftp %s:%s", formatedFileName, isFileStored));
      LOGGER.info("file upload success...");
    catch (IOException e) {

      LOGGER.error("An IOException has occured..." + e);
      e.printStackTrace();
    finally {
      if (ftpClient.isConnected()) {
        try {
          ftpClient.logout();
          ftpClient.disconnect();
          file.close();
        catch (IOException ioe) {
          LOGGER.error("An IOException has occured..." + ioe);
          ioe.printStackTrace();
        }
      }
    }
  }

  private static void setValues(Properties readPropertiesFile2) {

    if (readPropertiesFile2 != null) {

      sourceDirectory = readPropertiesFile2.getProperty("ftp.source.fileLocation");
      destinationFtpAddress = readPropertiesFile2.getProperty("destination.ftp.address");
      destinationFtpUserId = readPropertiesFile2.getProperty("destination.ftp.user");
      destinationFtpPassword = readPropertiesFile2.getProperty("destination.ftp.pass");
      destinationDirectory = readPropertiesFile2.getProperty("backup.fileLocation");
    }

  }

  /*
   * (non-Javadoc)
   
   * @see com.cv.ftp.read.FTPService#getFileViaFTP()
   */
  public String getFileViaFTP() {
    String name = null;
    setValues(readPropertiesFile);
    ftpClient = getFtpClient();
    OutputStream outputFile = null;
    try {

      boolean isDirChanged = ftpClient.changeWorkingDirectory(sourceDirectory);
      String[] fileNames = ftpClient.listNames();
      if (fileNames != null) {
        for (int i = 0; i < fileNames.length; i++) {
          name = fileNames[i];
          if (name != null) {
            outputFile = new FileOutputStream(destinationDirectory + name);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.retrieveFile(name, outputFile);
            outputFile.flush();
            outputFile.close();

            ftpClient.deleteFile(name);
          }
        }

      }

    catch (IOException e) {

      LOGGER.error("An IOException has occured..." + e);
      e.printStackTrace();
    finally {
      if (ftpClient.isConnected()) {
        try {
          ftpClient.logout();
          ftpClient.disconnect();
          if (outputFile != null) {
            outputFile.close();
          }
        catch (IOException ioe) {
          LOGGER.error("An IOException has occured..." + ioe);
          ioe.printStackTrace();
        }
      }
    }
    return null;
  }

  /**
   @return the ftpClient
   */
  public FTPClient getFtpClient() {
    ftpClient = new FTPClient();
    FTPClientConfig config = new FTPClientConfig();
    boolean error = false;
    int reply;
    try {
      ftpClient.connect(destinationFtpAddress);
      ftpClient.user(destinationFtpUserId);
      ftpClient.pass(destinationFtpPassword);
      reply = ftpClient.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
        LOGGER.error("FTP server refused connection.");
      }
      ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
      // Use passive mode as default because most of us are
      // behind firewalls these days.
      // ftpClient.enterLocalPassiveMode();
    catch (SocketException e) {

      LOGGER.error("An SocketException has occured..." + e);
      e.printStackTrace();

    catch (IOException e) {

      LOGGER.error("An IOException has occured..." + e);
      e.printStackTrace();

    }

    return ftpClient;
  }

  /**
   @param ftpClient
   *            the ftpClient to set
   */
  public void setFtpClient(FTPClient ftpClient) {
    this.ftpClient = ftpClient;
  }

  public String getDestinationFtpAddress() {
    return destinationFtpAddress;
  }

  public void setDestinationFtpAddress(String destinationFtpAddress) {
    FTPConnect.destinationFtpAddress = destinationFtpAddress;
  }

  public String getDestinationFtpUserId() {
    return destinationFtpUserId;
  }

  public void setDestinationFtpUserId(String destinationFtpUserId) {
    FTPConnect.destinationFtpUserId = destinationFtpUserId;
  }

  public String getDestinationFtpPassword() {
    return destinationFtpPassword;
  }

  public void setDestinationFtpPassword(String destinationFtpPassword) {
    FTPConnect.destinationFtpPassword = destinationFtpPassword;
  }

  public String getSourceDirectory() {
    return sourceDirectory;
  }

  public void setSourceDirectory(String sourceDirectory) {
    FTPConnect.sourceDirectory = sourceDirectory;
  }

  public String getDestinationDirectory() {
    return destinationDirectory;
  }

  public void setDestinationDirectory(String destinationDirectory) {
    FTPConnect.destinationDirectory = destinationDirectory;
  }

  private static Properties readPropertiesFile() {
    Properties props = new Properties();
    try {
      props.load(FTPConnect.class.getClassLoader().getResourceAsStream("input.properties"));
    catch (Exception e) {
      System.err.println("Problem while reading properties file!!!");
    }
    return props;
  }

  public static void main(String[] args) {

    FTPConnect ftpService = new FTPConnect();
    ftpService.getFileViaFTP();

  }

  public static void moveFile(String srcDir, String destDir) {
    File sourceFile = new File(srcDir);
    File destFile = new File(destDir);
    try {
      FileUtils.copyFile(sourceFile, destFile);
      FileUtils.forceDelete(sourceFile);
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}


This is pom.xml file having the entries of dependency jars and information to build the application .



	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.ftp.connect</groupId> <artifactId>FTPConnectionExample</artifactId> <version>1.0</version> <build> src <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <properties> <java.version>1.8</java.version> <log4j-version>1.2.17</log4j-version> </properties> <dependencies> <dependency> <groupId>net.sourceforge.jtds</groupId> <artifactId>jtds</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxrs</artifactId> <version>2.2.1.GA</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.0</version> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-vfs2</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>openxml4j</artifactId> <version>1.0-beta</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.9</version> </dependency> </dependencies> </project>


This is log4j.properties file having the entries for logging the information into the console/file.




#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

No comments:

Post a Comment