Tuesday, January 10, 2012

FTP Upload

package com.nmmc.collection.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import com.nmmc.collection.model.FTPUser;

public class FTPUpload {

    private final static int BUFFER_SIZE = 2048;

    public static void main(String args[]) throws Exception {
        FTPUser user = new FTPUser();
        user.setUserName("hyduser");
        user.setPassword("hyduser");
        user.setFilePath("c:/balu.txt");
        user.setAddress("10.10.10.11");
        uploadFile(user);
    }

    public static boolean uploadFile(FTPUser ftpUser) throws SocketException, IOException {
        FileInputStream in = null;
        boolean blnFileUploadStatus = false;
        FTPClient ftp = new FTPClient();
        ftp.connect(ftpUser.getAddress());
        ftp.login(ftpUser.getUserName(), ftpUser.getPassword());

        int reply = ftp.getReplyCode();

        if (FTPReply.isPositiveCompletion(reply)) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.setBufferSize(BUFFER_SIZE);
            String fileName = ftpUser.getFilePath();
            in = new FileInputStream(fileName);
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
            blnFileUploadStatus = ftp.storeFile(fileName, in);

            in.close();
        }
        ftp.disconnect();
        return blnFileUploadStatus;
    }
}

No comments: