Thursday, October 27, 2011

Java FTP client

If you are looking for Java FTP client I suggest you to look at Apache Commons Net library. There is a class FTPClient. It is very easy to use and has all the functionality you may want to have.
To use this library we have to download it from the official site or add maven dependency:
<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.0.1</version>
</dependency>
After this if we want to upload the file to the server we should do something like this:
public static boolean uploadFile(File file, String workingDirectory, String fileName) {
  FTPClient client = new FTPClient();
  try {
    client.connect(FTP_HOST, FTP_PORT);
    // After connection attempt, we have to check the reply code to
    // verify success.
    int reply = client.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
      System.err.println("FTP server refused connection.");
      return false;
    }
  
    client.login(FTP_USERNAME, FTP_PASSWORD);
    client.changeWorkingDirectory(workingDirectory);
    client.storeFile(fileName, new FileInputStream(file));
    client.logout();
    return true;
  } catch (SocketException e) {
    throw new RuntimeException(e);
  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    if (client.isConnected()) {
      try {
        client.disconnect();
      } catch (IOException ioe) {
        // swallow exception
        System.err.println("Cannot disconnect from the host");
      }
    }
  } 
}
If you need to download, delete or append file it would be pretty similar.
To get listing of directories you may need to enter local passive mode. Here is an example:
public static void printFiles(String workingDirectory) {
  FTPClient client = new FTPClient();
  try {
    client.connect(FTP_HOST, FTP_PORT);   
    // After connection attempt, we have to check the reply code to
    // verify success.
    int reply = client.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
      System.err.println("FTP server refused connection.");
    }
  
    client.enterLocalPassiveMode();
    client.login(FTP_USERNAME, FTP_PASSWORD);
    FTPFile[] files = client.listFiles(workingDirectory);
     
    for (FTPFile file : files) {
      System.out.println(file.getName());
    }
    client.logout();
  } catch (SocketException e) {
    throw new RuntimeException(e);
  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    if (client.isConnected()) {
      try {
        client.disconnect();
      } catch (IOException ioe) {
        // swallow exception
        System.err.println("Cannot disconnect from the host");
      }
    }
  }
}
It was easy wasn't it? To learn more see the documentation.