Java Development
Articles
Java FTP Source Code
Published: August 1, 2007
Print    Email

File Transfer Protocol is the protocol for exchanging files over the Internet. FTP works in the same way as HTTP for transferring Web pages from a server to a user's browser and SMTP for transferring electronic mail across the Internet in that, like these technologies, FTP uses the Internet's TCP/IP protocols to enable data transfer. The simplest way to access an FTP site is to use a SimpleFTP which is the a simple Java FTP client package. You can download it Here

try {
    SimpleFTP ftp = new SimpleFTP();
   
    // Connect to an FTP server on port 21.
    ftp.connect("ftp.somewhere.net", 21, "username", "password");
   
    // Set binary mode.
    ftp.bin();
   
    // Change to a new working directory on the FTP server.
    ftp.cwd("web");
   
    // Upload some files.
    ftp.stor(new File("webcam.jpg"));
    ftp.stor(new File("comicbot-latest.png"));
   
    // You can also upload from an InputStream, e.g.
    ftp.stor(new FileInputStream(new File("test.png")), "test.png");
    ftp.stor(someSocket.getInputStream(), "blah.dat");
   
    // Quit from the FTP server.
    ftp.disconnect();
}
catch (IOException e) {
}

The most attractive option for FTP functionality in Java is the Jakarta Commons Net library, which implements the client side of many basic Internet protocols.

 package examples;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPReply;

/***
 * This is an example program demonstrating how to use the FTPClient class.
 * This program connects to an FTP server and retrieves the specified
 * file.  If the -s flag is used, it stores the local file at the FTP server.
 * Just so you can see what's happening, all reply strings are printed.
 * If the -b flag is used, a binary transfer is assumed (default is ASCII).
 *


 * Usage: ftp [-s] [-b]
 *


 ***/
public final class ftp
{

    public static final String USAGE =
        "Usage: ftp [-s] [-b] \n" +
        "\nDefault behavior is to download a file and use ASCII transfer mode.\n" +
        "\t-s store file on server (upload)\n" +
        "\t-b use binary transfer mode\n";

    public static final void main(String[] args)
    {
        int base = 0;
        boolean storeFile = false, binaryTransfer = false, error = false;
        String server, username, password, remote, local;
        FTPClient ftp;

        for (base = 0; base < args.length; base++)
        {
            if (args[base].startsWith("-s"))
                storeFile = true;
            else if (args[base].startsWith("-b"))
                binaryTransfer = true;
            else
                break;
        }

        if ((args.length - base) != 5)
        {
            System.err.println(USAGE);
            System.exit(1);
        }

        server = args[base++];
        username = args[base++];
        password = args[base++];
        remote = args[base++];
        local = args[base];

        ftp = new FTPClient();
        ftp.addProtocolCommandListener(new PrintCommandListener(
                                           new PrintWriter(System.out)));

        try
        {
            int reply;
            ftp.connect(server);
            System.out.println("Connected to " + server + ".");

            // After connection attempt, you should check the reply code to verify
            // success.
            reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                System.err.println("FTP server refused connection.");
                System.exit(1);
            }
        }
        catch (IOException e)
        {
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException f)
                {
                    // do nothing
                }
            }
            System.err.println("Could not connect to server.");
            e.printStackTrace();
            System.exit(1);
        }

__main:
        try
        {
            if (!ftp.login(username, password))
            {
                ftp.logout();
                error = true;
                break __main;
            }

            System.out.println("Remote system is " + ftp.getSystemName());

            if (binaryTransfer)
                ftp.setFileType(FTP.BINARY_FILE_TYPE);

            // Use passive mode as default because most of us are
            // behind firewalls these days.
            ftp.enterLocalPassiveMode();

            if (storeFile)
            {
                InputStream input;

                input = new FileInputStream(local);

                ftp.storeFile(remote, input);

                input.close();
            }
            else
            {
                OutputStream output;

                output = new FileOutputStream(local);

                ftp.retrieveFile(remote, output);

                output.close();
            }

            ftp.logout();
        }
        catch (FTPConnectionClosedException e)
        {
            error = true;
            System.err.println("Server closed connection.");
            e.printStackTrace();
        }
        catch (IOException e)
        {
            error = true;
            e.printStackTrace();
        }
        finally
        {
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException f)
                {
                    // do nothing
                }
            }
        }

        System.exit(error ? 1 : 0);
    } // end main

}

If you have some budget, you can consider   Secure FTP Factory  which has components for secure file transfer protocols including FTPS (FTP over SSL both implicit and explicit modes), SFTP (FTP over SSH) and SCP (Secure Copy via SSH).



View Comments (0)
Latest Articles
Java Threads

Delete file using File.delete( ) method

Copying Files in Java

Downloading the Contents of a URL

Java FTP Source Code

Processing XML with Java

Generating Random Numbers

Java Lexical Structure

Serializing

Learning java
Latest Posts
Last news from Bahrain islands
Posted by ribrothetit

Please, help me
Posted by FthrOfIIIChlds

Beginners tutorial!
Posted by perz

Health and Beauty FOREVER
Posted by SKACTANDATE

buy xanax fergana
Posted by FleseeKip

Newsletter
Subscribe to our Newsletter!

Your Email: