Feb 24, 2011

Upload Files to FTP Server using Java



import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
// sun.net.TelnetOutputStream and sun.net.ftp.FtpClient are default classes in JavaSE6
// You can find the classes in ${JAVA_HOME}/jre/lib/rt.jar
// So you don't need to download other .jar file
// But you cannot find in general APIs
/**
* @param hostname FTP Server
* @param port Port Number
* @param username FTP Server Login Username
* @param password FTP Server Login Password
* @param source File to upload to FTP Server
* @param destination The name of file to upload to FTP Server
*/
public static void send(String hostname, int port, String username, String password, File source, String destination) throws IOException {
    FtpClient ftp = new FtpClient(hostname, port);
    ftp.login(username, password);
    ftp.binary();
    FileInputStream fos = new FileInputStream(source);
    TelnetOutputStream tos = ftp.put(destination);
    DataOutputStream dos = new DataOutputStream(tos);
    byte[] buffer = new byte[1024 * 1024];
    for (int length; (length = fos.read(buffer)) > 0;) {
        dos.write(buffer, 0, length);
    }
    tos.flush();
    tos.close();
    fos.close();
}

public static void send(String hostname, String username, String password, File source, String destination) throws IOException {
    send(hostname, 21, username, password, source, destination);
}


0 comments:

Post a Comment

Twitter Delicious Facebook Digg Google Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best Hostgator Coupon Code