Saturday, May 19, 2012

FTP Upload/Download with Java

The below java code will help us to Download/Upload files from/To FTP server.

import java.io.*;
import java.net.*;

public class FTPClient {
    public final String host;
    public final String user;
    protected final String password;
    protected URLConnection ftpurl;

    public FTPClient(String host, String user, String password) {
        this.host = host;
        this.user = user;
        this.password = password;
        this.ftpurl = null;
    }

    private URL createURL(String destfile) throws MalformedURLException {
        if (user == null)
            return new URL("ftp://" + host + "/" + destfile + ";type=i");
        else
            return new URL("ftp://" + user + ":" + password + "@" + host +"/" + destfile + ";type=i");
    }

    protected InputStream openDownloadStream(String destfile) throws Exception {
        URL url = createURL(destfile);
        ftpurl = url.openConnection();
        InputStream is = ftpurl.getInputStream();
        return is;
    }

    protected OutputStream openUploadStream(String targetfile) throws Exception {
        URL url = createURL(targetfile);
        ftpurl = url.openConnection();
        OutputStream os = ftpurl.getOutputStream();
        return os;
    }

    protected void close() {
        ftpurl = null;
    }

    public void Upload(String sourcefile, String destfile) {
        try {
            OutputStream os = openUploadStream(destfile);
            FileInputStream is = new FileInputStream(sourcefile);
            byte[] buf = new byte[33554432];
            int c;
            while (true) {
                c = is.read(buf);
                if (c <= 0)
                    break;
                os.write(buf, 0, c);
            }
            os.close();
            is.close();
            close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }
    }

    public void Download(String sourcefile, String destfile) {
        try {
            InputStream is = openDownloadStream(destfile);
            FileOutputStream os = new FileOutputStream(sourcefile);
            byte[] buf = new byte[41943040];//Buffer size set to 40 MB ,change based on the file size
            int c;
            while (true) {
                c = is.read(buf);
                if (c <= 0)
                    break;
                os.write(buf, 0, c);
            }
            is.close();
            os.close();
            close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment