Posts Tagged ‘FTP’

FTP connection with JAVA

Tuesday, August 25th, 2009

Java again gives us another tool.

What is FTP?

FTP protocol that allows us to send or receive data from one point to another, be it a PC, server, or any other node that is connected to a network.

Usually when you have a web host these accounts have FTP congratulate sending files from our pc to the server that is hosting our site.

Investigating around I found a FTP client library very useful, I have tried it and going great. The library JvFTP Client provides interesting tasks, including:

  • Uploading / downloading files
  • Uploading directories recursively
  • Concurrent data transfer
  • Data transfer mode passive / active
  • Swing components to display directories
  • Components AWTpara display directories

This tool is available in jvftp and can be used in two ways, you run directly the jar, or do your own programming, including the libraries in your project.

If you want to program your own example here I leave a little guide on how you can do, let’s see …

… The first thing to do is incorporate the packages downloaded from jvftp in your project. Then you import the libraries to the class in which you make the connection:

import cz.dhl.io.*;
import cz.dhl.ftp.*;
import java.io.IOException;

Now we create the connection, the connection to prepare the data before creating access the FTP site. Let’s start with the server:

FtpConnect cn = FtpConnect.newConnect("ftp://ftp.domain.com");

ftp.domain.com value which is the server you are connecting. Each ftp account that include at least the server name, username and password. To log in using that account is something like this:

// Username
cn.setUserName("username");

// Password
cn.setPassWord("password");

Then it creates an object of type FTP, which is responsible for rendering all the information from our FTP site.

Ftp ftp1 = new Ftp();

Now the connection to the FTP site to begin processing the respective tasks

ftp1.connect(cn);

A practical example to test the connection would be to show the current directory with their files:

CoFile dir = new FtpFile(ftp1.pwd(), ftp1);

// Make a list of files that have the current directory
CoFile cfls[] = dir.listCoFiles();
if ( cfls != null )
        for (int n = 0; n < cfls.length; n++)
                    System.out.println( cfls[n].getName() + (cfls[n].isDirectory() ? "/" : ""));

Finally, there is only close the connection.

ftp1.disconnect();

Download jvftp

Happy Programming!!! ;-)