com.kcs.core.utilities.FtpUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.kcs.core.utilities.FtpUtil.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.kcs.core.utilities;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;

/**
 *
 * @author vorawats
 */
public class FtpUtil {
    Logger logger = Logger.getLogger(FtpUtil.class);

    public FtpUtil() {
    }

    public static FTPClient openFtpConnect(String hostname, int port, String username, String password)
            throws Exception {
        FTPClient ftp = null;
        try {
            ftp = new FTPClient();
            ftp.setConnectTimeout(1000);
            ftp.connect(hostname, port);
            ftp.login(username, password);
            ftp.enterLocalPassiveMode();
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return ftp;
    }

    public static void closeFtpServer(FTPClient ftp) throws Exception {
        try {
            ftp.logout();
            ftp.disconnect();
        } catch (Exception ex) {
            throw ex;
        }
    }

    public static boolean putFile(String hostname, int port, String username, String password,
            String remoteFileName, String localFileName) throws Exception {
        FTPClient ftp = null;
        try {
            ftp = FtpUtil.openFtpConnect(hostname, port, username, password);
            if (null != ftp && ftp.isConnected()) {
                File firstLocalFile = new File(localFileName);
                InputStream inputStream = new FileInputStream(firstLocalFile);

                System.out.println("Start upload file");
                boolean done = ftp.storeFile(remoteFileName, inputStream);
                inputStream.close();
                if (done) {
                    System.out.println("file is uploaded successfully.");
                }
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Error : " + e.getMessage());
        } finally {
            FtpUtil.closeFtpServer(ftp);
        }
    }

    public static boolean putFileByStream(String hostname, int port, String username, String password,
            String remoteFileName, String localFileName) throws Exception {
        FTPClient ftp = null;
        boolean result = false;
        try {
            ftp = FtpUtil.openFtpConnect(hostname, port, username, password);
            if (null != ftp && ftp.isConnected()) {
                File localFile = new File(localFileName);
                InputStream inputStream = new FileInputStream(localFile);

                System.out.println("Start uploading file");
                OutputStream outputStream = ftp.storeFileStream(remoteFileName);
                byte[] bytesIn = new byte[4096];
                int read = 0;

                while ((read = inputStream.read(bytesIn)) != -1) {
                    outputStream.write(bytesIn, 0, read);
                }
                inputStream.close();
                outputStream.close();

                boolean completed = ftp.completePendingCommand();
                if (completed) {
                    System.out.println("file is uploaded successfully.");
                    result = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Error : " + e.getMessage());
        } finally {
            FtpUtil.closeFtpServer(ftp);
        }
        return result;
    }

    public static boolean getFile(String hostname, int port, String username, String password,
            String remoteFileName, String localFileName) throws Exception {
        FTPClient ftp = null;
        boolean result = false;
        try {
            System.out.println("File has been start downloaded.");
            ftp = FtpUtil.openFtpConnect(hostname, port, username, password);
            if (null != ftp && ftp.isConnected()) {
                File downloadFile = new File(localFileName);
                if (!FtpUtil.checkFileExists(remoteFileName, ftp)) {
                    System.out.println("File not found in server.");
                    throw new Exception("File not found in server.");
                }
                OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
                result = ftp.retrieveFile(remoteFileName, outputStream);
                outputStream.close();
            }
            System.out.println("File [" + remoteFileName + "] has been downloaded Complete.");
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Error : " + e.getMessage());
        } finally {
            FtpUtil.closeFtpServer(ftp);
        }
        return result;
    }

    public static boolean getFileByStream(String hostname, int port, String username, String password,
            String remoteFileName, String localFileName) throws Exception {
        FTPClient ftp = null;
        boolean result = false;
        try {
            ftp = FtpUtil.openFtpConnect(hostname, port, username, password);
            if (null != ftp && ftp.isConnected()) {
                System.out.println("File has been start downloaded..............");
                System.out.println("downloading file " + remoteFileName + " to " + localFileName + ".");
                InputStream inputStream = ftp.retrieveFileStream(remoteFileName);
                if (null == inputStream) {
                    throw new Exception("File not found in server.");
                } else {
                    File localFile = new File(localFileName);
                    BufferedOutputStream bOut = new BufferedOutputStream(new FileOutputStream(localFile));
                    int b;
                    long count = 0;
                    while ((b = inputStream.read()) > -1) {
                        bOut.write(b);
                        count++;
                    }
                    bOut.close();
                    inputStream.close();
                    System.out.println("download file " + remoteFileName + "(" + count + ")bytes to "
                            + localFileName + " done.");
                    if (count > 0) {
                        result = true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Error : File not found in server.");
        } finally {
            FtpUtil.closeFtpServer(ftp);
        }
        return result;
    }

    public static boolean getFileByStreamMultipleFile(String hostname, int port, String username, String password,
            List<String> listRemoteFileName, List<String> listLocalFileName) throws Exception {
        boolean result = false;
        try {
            System.out.println("File has been start downloaded.");
            int i = 0;
            for (String localFileName : listLocalFileName) {
                result = getFileByStream(hostname, port, username, password, listRemoteFileName.get(i++),
                        localFileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Error : File not found in server.");
        }
        return result;
    }

    public static boolean checkFileExists(String hostname, int port, String username, String password,
            String fileName) throws IOException, Exception {
        FTPClient ftp = null;
        boolean result = true;
        try {
            ftp = FtpUtil.openFtpConnect(hostname, port, username, password);
            if (null != ftp && ftp.isConnected()) {
                InputStream inputStream = ftp.retrieveFileStream(fileName);
                int returnCode = ftp.getReplyCode();
                if (inputStream == null || returnCode == 550) {
                    System.out.println("File [ " + fileName + " ] not found in server.");
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            FtpUtil.closeFtpServer(ftp);
        }
        return result;
    }

    public static boolean checkFileExists(String filePath, FTPClient ftpClient) throws IOException {
        InputStream inputStream = ftpClient.retrieveFileStream(filePath);
        int returnCode = ftpClient.getReplyCode();
        if (inputStream == null || returnCode == 550) {
            return false;
        }
        return true;
    }
}